Using the Mongoose / MongoDB $ addToSet Function for an Array of Objects

let's say I have this array property ('article') in the Mongoose schema:

articles: [ { kind: 'bear', hashtag: 'foo' }, { kind: 'llama', hashtag: 'baz', }, { kind: 'sheep', hashtag: 'bar', } ] 

how can i use

$ addToSet https://docs.mongodb.org/manual/reference/operator/update/addToSet/

add to this array by checking the hashtag value to see if it is unique?

For example, if I want to add the following object to the above array, I want Mongo to reject it as a duplicate:

 { kind: 'tortoise', hashtag: 'foo' } 

because the hashtag = foo is already taken.

The problem is that I know how to use $addToSet with simple arrays of integers ...

for example, if the articles look like this:

 articles: [ 1 , 5 , 4, 2] 

I would use $ addToSet like this:

 var data = { "$addToSet": { "articles": 9 } } model.update(data); 

but how can I do the same with an array of objects where the unique field is a string, in this case 'hashtag'? The docs don't make it clear, and it seems like I searched everywhere ...

thanks

+7
source share
2 answers

You need to use the $ne operator.

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

This will update the document only if there is no subdocument in the "article" array with a hashtag value of "foo".

As @BlakesSeven is mentioned in a comment

$addToSet becomes irrelevant when you check for one of the values, so it can also be $push for clarity of code. But the principle is true, since $addToSet works with the whole object, and not just with its part.

 Model.update({ { 'article.hashtag': { '$ne': 'foo' } }, { '$push': {'article': data } } ) 
+18
source
 // add the comment 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') }) 
0
source

Source: https://habr.com/ru/post/1235398/


All Articles