Reputation: 304
const options = {
$addToSet: { whoLikes: userId },
$inc: { likesCount: 1 },
new: true,
};
collection.findByIdAndUpdate({ _id: postId }, options)
What I want is increment likesCount only if whoLikes array length is get incremented. Right now likesCount incrementing all the time doesn't matter how many objects inside whoLikes array.
I'm using mongoose, node.js
Upvotes: 1
Views: 85
Reputation: 36104
findOneAndUpdate()
methodwhoLikes: { $ne: userId }
userId should not inside whoLikes
array$push
instead of $addToSet
new:true
const options = {
$push: { whoLikes: userId },
$inc: { likesCount: 1 }
};
collection.findOneAndUpdate(
{
_id: postId,
whoLikes: { $ne: userId }
},
options,
{ new: true }
)
Ex1: Add UserID that is not present
Ex2: Add UserID that is already present
Upvotes: 1