Book Image

Node.js By Example

Book Image

Node.js By Example

Overview of this book

Table of Contents (18 chapters)
Node.js By Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Showing the comments


We should update the API method that returns the pages as objects. Along with the title and description, we have to present a new comments property. Let's open backend/api/pages.js and create a function to fetch comments:

var getComments = function(pageId, callback) {
  var collection = db.collection('content');
  collection.find({ 
    $query: {
      pageId: pageId
    },
    $orderby: {
      date: -1
    }
  }).toArray(function(err, result) {
    result.forEach(function(value, index, arr) {
      delete arr[index].userId;
      delete arr[index]._id;
    });
    callback(result);
  });
}

The key moment in the preceding method is the forming of the MongoDB query. This is the place where we filter the posts and fetch only those that are made for the page that matches the passed ID. The following is the updated code corresponding to the GET request:

getDatabaseConnection(function(db) {
  var query;
  if(params && params.id) {
    query = { _id: ObjectId(params...