Updated fields only if addToSet get updated

 const options = {
    $addToSet: { whoLikes: userId },
    $inc: { likesCount: 1 },
    new: true,
  };

collection.findByIdAndUpdate({ _id: postId }, options)

What I want is increment likesCount only if whoLikes gets a new record. Right now likesCount incrementing all the time doesn’t matter if new records has been inserted or ot in whoLikes array. Any idea how to achieve it with one query?

I’m using mongoose, node.js

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.