I have a code that allows to a user to like a post created by author ,the problem of this code that is always pushing value to mongodb
even the if the user is already existing in DB and also already liked the post
what I tried is below and I didn't succeed explained with some comments
const like = function (req, res, next) {
User.findOne({ 'events._id': req.params.id }).exec((err, obj) => {
if (!obj) return console.log("Does not exist.", null);
//console.log(obj);
for (var i = 0; i < obj.events.length; i++) {
if (obj.events[i]._id === req.params.id) {
console.log("Like here 1")
if (obj.events[i].likes.length) {
for (let j = 0; j < obj.events[i].likes.length; j++) {
console.log("like here 2")
if (obj.events[i].likes[j].by !== req.session.user ) {
console.log("data will be pushed")
obj.events[i].likes.push({ by: req.session.user });
obj.notifications.push({
msg: `@${req.session.user} liked your post.`,
link: `/u/${req.body.author}`,
time: new Date()
});
obj = new User(obj);
obj.save(err => {
console.log(err, true);
});
} else if (obj.events[i].likes[j].by === req.session.user ) {
console.log("here nothing will be pushed")
console.log('already liked')
return res.json('Already Liked!!')
}
}
} else {
console.log("in this case if(obj.events[i].likes.length) =0")
obj.events[i].likes.push({ by: req.session.user });
obj.notifications.push({
msg: `@${req.session.user} liked your post.`,
link: `/u/${req.body.author}`,
time: new Date()
});
obj = new User(obj);
obj.save(err => {
console.log(err, true);
});
}
}
}
});
}
the result that I get always is this
What I'm looking for is below :
1- when a user click on the button, the code check of the user already liked the post or not using obj.events[i].likes[j].by !== req.session.user
2- if the user already exists and liked the post then return liked
3- if the
obj.events[i].likes.length
=0 then a new value is pushed to db
Hope I explained everything could it be possible to help me with this issue?