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 number of likes


We keep the likes in an array. It is easy to count the elements there and find out how many times a post is liked. We will make two small changes that will make this possible. The first one is in the API, which is the place where we prepare the post objects:

// backend/api/content.js
result.forEach(function(value, index, arr) {
  arr[index].id = ObjectId(value._id);
  arr[index].ownPost = user._id.toString() ===  ObjectId(arr[index].userId).toString();
  arr[index].numberOfLikes = arr[index].likes ?  arr[index].likes.length : 0;
  delete arr[index].userId;
  delete arr[index]._id;
});

A new numberOfLikes property is attached. The records did not have a likes property in the beginning. So, we have to check whether it exists before we use it. If we have numberOfLikes variable, we can update the label of the Like button in the frontend to the following code:

<input type="button" value="Like ({{posts[index].numberOfLikes}})" on-click="like:{{posts[index].id}}" /&gt...