假设我在Mongoose架构上有这个数组属性("articles"):
articles: [
{
kind: 'bear',
hashtag: 'foo'
},
{
kind: 'llama',
hashtag: 'baz',
},
{
kind: 'sheep',
hashtag: 'bar',
}
]
我如何使用
$addToSethttps://docs.mongodb.org/manual/reference/operator/update/addToSet/
通过检查hashtag的值来添加到这个数组中,看看它是否是唯一的?
例如,如果我想将以下对象添加到上面的数组中,我希望Mongo将其作为副本"拒绝":
{
kind: 'tortoise',
hashtag: 'foo'
}
因为hashtag=foo已经被使用了。
问题是,我只知道如何将$addToSet
与简单的整数数组一起使用。。。
例如,如果文章看起来像这样:
articles: [ 1 , 5 , 4, 2]
我会这样使用$addToSet:
var data = {
"$addToSet": {
"articles": 9
}
}
model.update(data);
但是,对于唯一字段是字符串的对象数组,在这种情况下是"hashtag",我如何才能完成同样的事情呢?医生没有说清楚,我好像到处都找过了。。
感谢
您需要使用$ne
运算符。
var data = { 'kind': 'tortoise', 'hashtag': 'foo' };
Model.update(
{ 'articles.hashtag': { '$ne': 'foo' } },
{ '$addToSet': { 'articles': data } }
)
只有当"article"数组中没有hashtag值等于"foo"的子文档时,才会更新文档。
正如@BlakeSeven在评论中提到的那样
一旦测试其中一个值的存在,
$addToSet
就变得不相关了,所以为了代码的清晰性,这也可以是$push
。但原理是正确的,因为$addToSet
对整个对象有效,而不仅仅是它的一部分
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')
})