| I'm a newbie in JS, NodeJS, Mongodb and I am trying to figure out my issue have. exports.like = function (req, res, next) {
PostModel.findByIdAndUpdate(req.params.postIdLike, req.body, {new : true}, function (err, post) {
if (err) {
console.log(this.getErrorMessage(err));
return next(err);
} else {
var numberPeopleLike = post.Like.PeopleLike.length;
var currentUserID = req.body.CurrentUserID;
console.log(numberPeopleLike);
if (numberPeopleLike === 0) {
post.Like.PeopleLike.push({id: currentUserID, flag: true});
post.Like.NumberLike += 1;
var data = {
value: post,
message: "Like",
status: 1
};
res.json(data);
/* Can't save into collection */
next();
} else {
// post like != null
console.log("numberPeopleLike");
for (var i = 0; i < numberPeopleLike; i++) {
if (post.Like.PeopleLike[i].id === currentUserID && post.Like.PeopleLike[i].flag === true) {
// user Liked
post.Like.NumberLike -= 1;
post.Like.PeopleLike[i].flag = false;
var data = {
value: post,
message: "Undo Like",
status: 0
};
res.json(data);
next();
} else {
// user don't like
post.Like.NumberLike += 1;
post.Like.PeopleLike.push({id: currentUserID, flag: true});
var data = {
value: post,
message: "Like",
status: 1
};
res.json(data);
next();
}
}
}
}
});
};
My Problem : The findByIdAndUpdate function isn't update result code in if(numberPeopleLike === 0) condition. Although data json has value , the result can't update on collections. What's wrong? [UPDATE] When I implement with PUT method to excute function (Update )then Value of data in if(numberPeopleLike === 0 ) condition
{
"value": {
"_id": "5717938a857e9c8a0e71a512",
"IDMemberProfile": "5711114c2b5ecdf11a23947d",
"Title": "test",
"Content": "test",
"Status": 1,
"__v": 0,
"Like": {
"NumberLike": 1,
"PeopleLike": [
{
"id": "570f932dfc642a4f1df5b450",
"flag": true,
"_id": "5717a9e42ae3ca5f12180844"
}
]
},
"PostTime": "2016-04-20T14:34:50.973Z"
},
"message": "Like",
"status": 1
}
|