mongodb插入子文档

时间:2015-08-24 12:48:34

标签: angularjs node.js mongodb express

我尝试使用nodejs app和mongo db,

帖子列表

     post1:
{ 
        "_id" : ObjectId("55da3eba9ec57c443d0c2287"),
        post :  Hello i am a post
}   


     post2
{
        "_id" : ObjectId("55da3db157c0bb2d3d9555c9")
        post : hello 2
}

我希望在post1中有一个新文档

      post1:
{  
         "_id" : ObjectId("55da3eba9ec57c443d0c2287"),
         post :  Hello i am a post
         comments : {
                   comment : hello i am a comment ,
                   user : req.session.user.username ,
                    }
}

我如何插入或更新post1

1 个答案:

答案 0 :(得分:0)

假设您有关于格式的收集帖子:

{
  _id:<id>,
  name: <name>,
  content: <content>,
  comments: [<comment>,...]
}

您可以通过以下方式添加评论:

db.posts.update({_id: <post id>}, {$push: {comments: {comment: 'hello...', user: user}});