Need to push data in nested subdocument array

心不动则不痛 提交于 2021-02-10 14:37:53

问题


I need to push data in nested subdocument array(replyComment):

This is an example of a document from my database:

{
  comments: [
    {
      replyComment: [],
      _id: 601a673735644c83e0aa1be3,
      username: 'xyz123@gmail.com',
      email: 'xyz213@gmail.com',
      comment: 'test123'
    },
    {
      replyComment: [],
      _id: 601a6c94d1653c618c75ceae,
      username: 'xyz123@gmail.com',
      email: 'xyz123@gmail.com',
      comment: 'reply test'
    }
  ],
  _id: 601a3b8038b13e70405cf9ea,
  title: 'latest test',
  snippet: 'latest test snippet',
  body: 'latest test body',
  createdAt: 2021-02-03T05:58:24.123Z,
  updatedAt: 2021-02-03T12:28:33.237Z,
  __v: 7
}

I am also mentioning my code snippet:

app.post('/:id/replyComment',(req,res) => { 
  const replyComm = new Comment(req.body);
  Topic.findById(req.params.id)
  .then((result) => {
    topic = result,
    console.log(topic);
    topic.update({_id:req.params.id, "comments._id": req.body.comment_id},
      { $push: {"comments.$.replyComment": {replyComment: replyComm}}}
    )
    topic.save()
    .then((result) => {
      // console.log(result);
        res.send({
          text: "Replied",
        })
    })
    .catch((err) => {
        console.log(err);
    });
  })
});

By running the request I am not getting any error but still the same documented is getting printed on my terminal and there is no change in "replyComment" subarray. Pls suggest how to make this work or any alternate method.


回答1:


I prefer to use objects instead of arrays by converting objects to the array Object.keys(data.comments)

{
  comments: 
    {
     '601a673735644c83e0aa1be3':{
        username: 'samyakjain971@gmail.com',
        email: 'samyakjain971@gmail.com',
        comment: 'test123'
      }
    },
    {
     '601a6c94d1653c618c75ceae':{
        username: 'samyakjain971@gmail.com',
        email: 'samyakjain971@gmail.com',
        comment: 'reply test'
     }
    },
  _id: 601a3b8038b13e70405cf9ea,
  title: 'latest test',
  snippet: 'latest test snippet',
  body: 'latest test body',
  createdAt: 2021-02-03T05:58:24.123Z,
  updatedAt: 2021-02-03T12:28:33.237Z,
  __v: 7
}



回答2:


define topic variable like this :

let topic = result;
console.log(topic);
topic.update({_id:req.params.id, "comments._id": req.body.comment_id},
    { $push: {"comments.$.replyComment": {replyComment: replyComm}}}
)


来源:https://stackoverflow.com/questions/66027692/need-to-push-data-in-nested-subdocument-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!