Mustafa Deniz
Mustafa Deniz

Reputation: 1668

mongodb insert in subdocuments

i trying nodejs app and mongo db ,

post list

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


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

and i want a new document in post1

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

how can i insert or update post1

Upvotes: 0

Views: 615

Answers (1)

Andreas Møller
Andreas Møller

Reputation: 849

assuming you have a collection posts on the format:

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

you can add a comment by running:

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

Upvotes: 1

Related Questions