如何将obj插入数组Mongoose

时间:2017-02-05 17:19:08

标签: mongodb mongoose

我有这个架构

var postSchema = new Schema({
    category: 'Home',
    body: 'sometext',
    comments: [{
        nickName: 'Meron', 
        comment: 'Hello',  
        date: 'Feb 2 2017, 23:32', 
            commentUnders: [{
                nickName: 'Storseses', 
                comment: 'It's our dat', 
                date: 'Feb 5 2017, 22:03'
            }]
        }]
});

我如何findByIdAndUpdate评论下?我已经在评论中发表了一条评论,其中包含id" 5897518c0a913a842cc041cf"。我试过这个解决方案但不起作用:

   Post.findByIdAndUpdate( {'comments._id': '5897518c0a913a842cc041cf'},
        {
            $push: {
                   commentUnders: {
                       "comment" : "Так, что мне делать-то?",
                       "nickName" : "Great",
                       "date" : Date.now()
                   }
              } 
        }, function(err, data) { 
              if (err) {console.log(err); } 
              console.log(data); 
        });

1 个答案:

答案 0 :(得分:1)

使用$ positional operator findOneAndUpdate() 功能代替 findByIdAndUpdate() 来更新匹配的comments数组:< / p>

Post.findOneAndUpdate(
    { "comments._id": "5897518c0a913a842cc041cf" },
    {
        "$push": {
            "comments.$.commentUnders": {
                "comment" : "Так, что мне делать-то?",
                "nickName" : "Great",
                "date" : Date.now(),
            }
        }
    }, 
    function(err, data) { 
        if (err) console.log(err); 
        console.log(data); 
    }
);
相关问题