Sunday, 13 October 2019

How to insert into nest document using mongoose post has many comments , comment has many replies

My posts Document has the following structure:

{
    "_id" : ObjectId("5d9df11b0e0a6e032bf3117f"),
    "body" : "Sample content post.",
    "date" : ISODate("2019-10-07T11:02:40.126Z"),
    "comments" : [            
        {
            "comment" : "comment on post",
            "_id" : ObjectId("5d9df46e0e0a6e032bf31182"),
            "replies" : [
                { 
                    "reply" : "reply to comment ",
                    "_id" : ObjectId("5d9bec26301798056bb07ab5")
                },
                      ]
        }, 
    ],

}

I want to add a new reply to a specific post and comments of this request data {data: req.body}

{
  "data": {
    "id_post": "5d9df11b0e0a6e032bf3117f",
    "id_comment": "5d9df46e0e0a6e032bf31182",
    "new_reply": "Another new reply to comment"
  }
}

I am using nodejs/express/mongoose, can you help to guide how should I add a new reply.

// find the post by id
// then find comments under that post
// then insert reply under that comment

 router.post("/saveReply", function(req, res, next){
  let addReply = async ()=>{
    try{
         await Post.update(
               {
                 "_id" : req.body.id_post,
                 "comments._id" : req.body.id_comment 
               },
              {
              "$addToSet" : { 
                  "comments.$.replies" : {
                              "reply" : req.body.reply,
                                 }
                            }
              }
      );
      return res.send({ msg: req.body });


  }
  catch(e){
    console.error(e)
  }
  }

});


from How to insert into nest document using mongoose post has many comments , comment has many replies

No comments:

Post a Comment