Using Mongoose / MongoDB $addToSet functionality on array of objects

前端 未结 2 1449
清酒与你
清酒与你 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 } }
    )
    
    0 讨论(0)
  • 2020-12-05 15:34
    // 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')
                            })
    
    0 讨论(0)
提交回复
热议问题