简体   繁体   English

mongoose:在数组内应用 object 值的 $addToSet?

[英]mongoose: applying $addToSet of the object value inside the array?

game_data: [{
   id: 'HUH',
   name: 'GTA'
   story: 'ahhhh'
}]

I have a field like above.我有一个像上面这样的字段。 I want to check incoming data to avoid duplicate on the value id .我想检查传入的数据以避免重复值id

incomingg_dataA: {
       id: 'HUH',
       name: 'Dota2'
       story: 'hmmm'
    }

Like this case, if the incomingg_dataA contains the same id HUH .像这种情况下,如果incomingg_dataA包含相同的 id HUH I want to use that value to $addToSet .我想将该值用于$addToSet If the id is different如果id不同

incomingg_dataB: {
       id: 'HUUUH',
       name: 'Dota2'
       story: 'hmmm'
    }

then, it would be那么,这将是

game_data: [{
   id: 'HUH',
   name: 'GTA'
   story: 'ahhhh'
}, 
{
   id: 'HUUUH',
   name: 'Dota2'
   story: 'hmmm'
}];

I could do the entire document as $addToSet but then, I am kinda afraid that someone will just change the story part and it will still be registered.我可以将整个文档作为$addToSet ,但是我有点担心有人会更改story部分并且它仍然会被注册。

Is there any way that I can do this with $addToSet or do I just have to do the.find() and callback function?有什么方法可以用$addToSet做到这一点,还是我只需要做.find() 和回调 function?

You have to add the $ne condition in your find query with the id value you want to avoid duplicate.您必须在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM