Hello @Dmitriy_Blot, welcome to the MongoDB Community forum!
You may want to use the findOneAndUpdate
method in this case. Since, you want to update on a condition in addition to the _id
filter.
const filter = { _id: postId, whoLikes: { $ne: userId }}
const update = {
$addToSet: { whoLikes: userId },
$inc: { likesCount: 1 }
}
const options = { new: true }
Run the update:
collection.findOneAndUpdate(filter, update, options)
The above update will increment likesCount
only if whoLikes
gets a new record.