1

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: '[email protected]',
      email: '[email protected]',
      comment: 'test123'
    },
    {
      replyComment: [],
      _id: 601a6c94d1653c618c75ceae,
      username: '[email protected]',
      email: '[email protected]',
      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.

2
  • topic.comments.id is a variable, not a function, why are you trying to do topic.comments.id(req.params.id)? Commented Feb 3, 2021 at 12:42
  • Ohhh. I have edited the question pls look at it again. @J.F Commented Feb 3, 2021 at 12:58

2 Answers 2

0

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

{
  comments: 
    {
     '601a673735644c83e0aa1be3':{
        username: '[email protected]',
        email: '[email protected]',
        comment: 'test123'
      }
    },
    {
     '601a6c94d1653c618c75ceae':{
        username: '[email protected]',
        email: '[email protected]',
        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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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}}}
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.