Get pushed element to mongoose array in the callback function

Viewed 60

The schema of the document is given below:

author: String,
    
    title: String, 
    comments:[
        {
            commentAuthor: String,
            comment: String,
            dateOfComment: String
        }
    ]

I am trying to push a new comment to the comments array as given below:

SocialPost.findOneAndUpdate({_id: req.body.id},{$push:{comments: req.body}}, function(err, result){
        if(err) res.send(err);
        else res.json(result);
    })

The comment is being pushed successfully but what I want is that the callback function should return the pushed comment along with the mongoose unique ObjectId so that I can return the comment to the front-end. But the result contains the entire document, which I don't need.

Please help me to find how can I achieve this?

Thank You.

1 Answers

You can do this

let comment = result.comments[result.commetns.length - 1];
res.json(comment);

you will have access to the comment and its id in the comment object

Related