在对象数组上使用 Mongoose/MongoDB $addToSet 功能 [英] Using Mongoose / MongoDB $addToSet functionality on array of objects
问题描述
假设我在 Mongoose 模式上有这个数组属性('articles'):
say I have this array property ('articles') on a Mongoose schema:
articles: [
{
kind: 'bear',
hashtag: 'foo'
},
{
kind: 'llama',
hashtag: 'baz',
},
{
kind: 'sheep',
hashtag: 'bar',
}
]
如何使用
$addToSet https://docs.mongodb.org/manual/reference/operator/update/addToSet/
通过检查 hashtag 的值来添加到这个数组中以查看它是否唯一?
to add to this array by checking the value of hashtag to see if it's unique?
例如,如果我想将以下对象添加到上述数组中,我希望 Mongo 将其拒绝"为重复项:
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'
}
因为 hashtag=foo 已经被占用了.
because hashtag=foo has already been taken.
问题是我只知道如何将 $addToSet
与简单的整数数组一起使用...
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]
我会像这样使用 $addToSet:
I would use $addToSet like this:
var data = {
"$addToSet": {
"articles": 9
}
}
model.update(data);
但是我怎样才能用唯一字段是字符串的对象数组完成同样的事情,在这种情况下是'hashtag'?文档没有说明这一点,似乎我到处搜索..
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..
谢谢
推荐答案
您需要使用 $ne
运算符.
You need to use the $ne
operator.
var data = { 'kind': 'tortoise', 'hashtag': 'foo' };
Model.update(
{ 'articles.hashtag': { '$ne': 'foo' } },
{ '$addToSet': { 'articles': data } }
)
只有在article"数组中没有hashtag值为foo"的子文档时,才会更新文档.
This will update the document only if there is no sub document in the "article" array with the value of hashtag equals to "foo".
正如评论中提到的@BlakesSeven
As @BlakesSeven mentioned in the comment
$addToSet
变成一旦您测试其中一个值的存在,则无关紧要,因此这也可能是 $push
代码清晰.但原则是正确的,因为 $addToSet
适用于整个对象,而不仅仅是其中的一部分.
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 } }
)
这篇关于在对象数组上使用 Mongoose/MongoDB $addToSet 功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!