MongoDB/Mongoose - Adding an object to an array of objects only if a certain field is unique MongoDB/Mongoose - Adding an object to an array of objects only if a certain field is unique mongoose mongoose

MongoDB/Mongoose - Adding an object to an array of objects only if a certain field is unique


If you look into the documentation on your method you will see that the parameters passed are not in the proper order.

findByIdAndUpdate(id, update, options, callback)

I would use update instead and have your id and portal.events.eventId": { $ne: req.body.eventId } part of the initial filter followed by $addToSet: { "portal.events": req.body }

Something among these lines:

UserModel.update(  {      "_id": mongoose.Types.ObjectId(userId),      "portal.events.eventId": { $ne: req.body.eventId }  },  { $addToSet: { "portal.events": req.body } },  { new: true });


You need to include your eventId check into condition part of your query. Because you're usig findByIdAndUpdate you can only pass single value matched against _id as a condition. Therefore you have to use findOneAndUpdate to specify custom filtering condition, try:

UserModel.findOneAndUpdate(    { _id: userId, "portal.events.eventId": { $ne: req.body.eventId } },    { $addToSet: { "portal.events": req.body } },    { new: true });