TrendRadars > Technology > Develop > Pushing Object to Array inside of another Array in Mongoose/JS
Pushing Object to Array inside of another Array in Mongoose/JS
Pushing Object to Array inside of another Array in Mongoose/JS,I am trying to push an object to an array that is inside of another Array in Mongoose. Basically like comments for comments. Here is the structure of my schema here: const Schema = new mongoose.Sch...

Pushing Object to Array inside of another Array in Mongoose/JS

I am trying to push an object to an array that is inside of another Array in Mongoose. Basically like comments for comments. Here is the structure of my schema here:

const Schema = new mongoose.Schema ({  name: {type: String, required: true},  description: {type: String, required: true},  topics: [{name: String, description: String, responses: [{name: String, description: String}]});

And this is what I have tried so far:

Model.findOneAndUpdate({$and: [{_id: req.body.classId}, {topics: {$elemMatch: {_id: req.body.id}}}]}, {$push: {responses: {name: req.body.name, description: req.body.description}}}, function(err, result){  res.send(result);});

This doesn’t create any errors and result isn’t empty is I console.log it. I also tried to do it without $and, like this: {_id: req.body.classId, 'topics._id': req.body.id'} which didn’t work either.Can you also go one level deeper?

<——-Answers———->

You should specify { new: true } if you want to return the updated document:

Model.findOneAndUpdate(  {     _id: req.body.classId,    'topics._id': req.body.id  },  {    $push: {      responses: { name: req.body.name, description: req.body.description },    },  },  { new: true },  function (err, result) {    res.send(result);  });