Using Mongoose / MongoDB $addToSet functionality on array of objects

前端 未结 2 1462
清酒与你
清酒与你 2020-12-05 14:33

say I have this array property (\'articles\') on a Mongoose schema:

articles: [ 

 {
  kind: \'bear\',
  hashtag: \'foo\'    
 },

 {
  kind: \'llama\',
  ha         


        
2条回答
  •  悲&欢浪女
    2020-12-05 15:17

    You need to use the $ne operator.

    var data = { 'kind': 'tortoise', 'hashtag': 'foo' };
    Model.update(
        { 'articles.hashtag': { '$ne': 'foo' } }, 
        { '$addToSet': { 'articles': data } }
    )
    

    This will update the document only if there is no sub document in the "article" array with the value of hashtag equals to "foo".

    As @BlakesSeven mentioned in the comment

    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 } }
    )
    

提交回复
热议问题