![](/img/trans.png)
[英]Mongoose: Not able to add/push a new object to an array with $addToSet or $push
[英]mongoose: applying $addToSet of the object value inside the array?
game_data: [{
id: 'HUH',
name: 'GTA'
story: 'ahhhh'
}]
我有一個像上面這樣的字段。 我想檢查傳入的數據以避免重復值id
。
incomingg_dataA: {
id: 'HUH',
name: 'Dota2'
story: 'hmmm'
}
像這種情況下,如果incomingg_dataA
包含相同的 id HUH
。 我想將該值用於$addToSet
。 如果id不同
incomingg_dataB: {
id: 'HUUUH',
name: 'Dota2'
story: 'hmmm'
}
那么,這將是
game_data: [{
id: 'HUH',
name: 'GTA'
story: 'ahhhh'
},
{
id: 'HUUUH',
name: 'Dota2'
story: 'hmmm'
}];
我可以將整個文檔作為$addToSet
,但是我有點擔心有人會更改story
部分並且它仍然會被注冊。
有什么方法可以用$addToSet
做到這一點,還是我只需要做.find() 和回調 function?
您必須在 find 查詢中添加$ne
條件以及要避免重復的id
值。
db.col.update({
// All the find conditions you want
// Plus the below condition
"game_data.id": {"$ne": incomingg_dataB['id']}, // Updated only when the `id` is not already present in the array
}, {
"$push": {
"game_data": incomingg_dataB,
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.