say I have this array property ('articles') on a 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/
to add to this array by checking the value of hashtag to see if it's 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 hashtag=foo has already been taken.
The problem is that I only know how to use $addToSet
with simple arrays of integers...
for example, if articles looked 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 accomplish the same thing with an array of objects where the unique field is a string, in this case 'hashtag'? The docs don't make this clear and it seems like I have searched everywhere..
thanks