say I have this array property (\'articles\') on a Mongoose schema:
articles: [
{
kind: \'bear\',
hashtag: \'foo\'
},
{
kind: \'llama\',
ha
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 } }
)
// add the comment's id to the commentsList :
// share.comments.commentsList.addToSet(callback._id);
share.update(
{ '$push': {'comments.commentsList': mongoose.Types.ObjectId(callback._id) } }
, function(){
console.log('added comment id to the commentsList array of obectIds')
})