Using Mongoose / MongoDB $addToSet functionality on array of objects

You need to use the $ne operator.

var data = { 'kind': 'tortoise', 'hashtag': 'foo' };
Model.update(
    { 'articles.hashtag': { '$ne': 'foo' } }, 
    { '$addToSet': { 'articles': data } }
)

This will update the document only if there is no sub document in the “article” array with the value of hashtag equals to “foo”.

As @BlakesSeven mentioned in the comment

The $addToSet becomes irrelevant once you are testing for the presence of one of the values, so this may as well be a $push for code clarity. But the principle is correct since $addToSet works on the whole object and not just part of it.

Model.update({ 
    { 'articles.hashtag': { '$ne': 'foo' } }, 
    { '$push': {'articles':  data } }
)

Leave a Comment

tech