I am implementing an upvote (and downvote) system for users using node.js and mongoose mongodb, this is the logic:
if (req.body.vote === 'up') {
Posts.bulkWrite([
{
updateOne: {
filter: {
"_id": req.params.postId,
"votes.up": req.user._id
},
update: {
$pull: { "votes.up": req.user._id },
$inc: { "upvoteCount": -1 }
}
}
},
{
updateOne: {
filter: {
"_id": req.params.postId,
"votes.up": { $ne: req.user._id },
"votes.down": req.user._id
},
update: {
$push: { "votes.up": req.user._id },
$inc: { "upvoteCount": 1, "downvoteCount": -1 },
$pull: { "votes.down": req.user._id }
}
}
},
{
updateOne: {
filter: {
"_id": req.params.postId,
"votes.up": { $ne: req.user._id }
},
update: {
$push: { "votes.up": req.user._id },
$inc: { "upvoteCount": 1 }
}
}
}
])
}
the clear problem is that, in this case, if the user upvotes, it works, but then when trying to remove the upvote, via clicking the upvote button again, it is initially removed by the first update, but then added again because the third update sees the already modified document, meaning it updates it twice, I would like to limit it to only one modification. I thought of using a counter, but where do I put the if..? There might be a great architectural problem with this logic.
I am quite new to this, any advice/solution is appreciated.