[英]Using Mongoose / MongoDB $addToSet functionality on array of objects
說我在貓鼬模式上有這個數組屬性(“文章”):
articles: [
{
kind: 'bear',
hashtag: 'foo'
},
{
kind: 'llama',
hashtag: 'baz',
},
{
kind: 'sheep',
hashtag: 'bar',
}
]
我該如何使用
$addToSet https://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”的子文檔時,才會更新文檔。
正如評論中提到的@BlakesSeven
一旦您測試其中一個值的存在,
$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')
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.