The only thing I need is to remove the like if the user has already liked the post. I've tried with filter and other methods and it doesn't work.
The add like part is working normally. Like is an Array of objects.
If anyone can help..
const id = req.params.id;
const post = await Posts.findOne({ _id: id });
const token = getToken(req);
const user = await getUserByToken(token);
post.like = {
_id: user._id,
name: user.name,
};
const liked = post.like.find((likeExist) => {
return likeExist._id == user._id;
});
if (liked !== undefined) {
const newLike = await Posts.findByIdAndUpdate(post, {
$pull: { like: post.like },
});
res.status(200).json({
Likes: newLike.like,
});
return
} else {
const newLike = await Posts.findByIdAndUpdate(post._id, {
$push: { like: post.like },
});
res.status(200).json({
Likes: newLike.like,
});
}
}
CodePudding user response:
You are assigning an object to a post.like
post.like = {
_id: user._id,
name: user.name,
};
and then using find method on it
const liked = post.like.find((likeExist) => {
return likeExist._id == user._id;
});
That doesn't make sense.
Try something like this:
const id = req.params.id;
const post = await Posts.findOne({ _id: id });
const user = await getUserByToken(token);
const index = post.like.findIndex((like) => {
return like._id == user._id;
});
if (index > -1) {
// already liked, remove it
post.like.splice(index, 1);
} else {
// add a like
post.like.push({
_id: user._id,
name: user.name
});
}
// no need to use Posts.findByIdAndUpdate
// just save the post
post.save();
res.status(200).json({
Likes: post.like
});
CodePudding user response:
You are calling Posts.findByIdAndUpdate
and not giving an id for the removing like part. Try with this:
const id = req.params.id;
const post = await Posts.findOne({ _id: id });
const token = getToken(req);
const user = await getUserByToken(token);
post.like = {
_id: user._id,
name: user.name,
};
const liked = post.like.find((likeExist) => {
return likeExist._id === user._id;
});
if (!liked) {
const newLike = await Posts.findByIdAndUpdate(post._id, {
$pull: { like: post.like },
});
res.status(200).json({
Likes: newLike.like,
});
return
} else {
const newLike = await Posts.findByIdAndUpdate(post._id, {
$push: { like: post.like },
});
res.status(200).json({
Likes: newLike.like,
});
}
}