Mongoose: How do I replace an array of subdocuments? Mongoose: How do I replace an array of subdocuments? mongoose mongoose

Mongoose: How do I replace an array of subdocuments?


You can use the _underscore library to filter (reject) the object you want to remove

Here an example how to remove something from an array without foreach.

var _und = require('underscore');var array = [{_id:1, title:'object one'}, {_id:2, title:'object two'}, {_id:3, title: 'object three' }]    the_target = 'object two';    new_array = _und.reject(array, function(item){       return item.title === target;    })

The expected result should be:

=> [{_id:1, title:'object one'}, {_id:3, title:'object three'}]

If you know the id, even better.

All you have to do then is empty your subdocs by doing this:

var mytargetarray = [];    mytargetarray.push(new_array);    mytargetarray.save();

If you want to replace the whole subdoc array, why not just replacing them:

req.user.contacts = [];req.user.contacts.push(req.body.contacts);

save and done.

Hope that helps a bit.

Just a hint, in mongodb you work with object arrays, you can simple replace every value:

// active data from databaseuser.name = 'test user';// now just give the object a new valueuser.name = 'new name';// and save .. doneuser.save();


there is a better way using findOneAndUpdate to do this.

First you create Mongoose Documents for all the objects in the array (which will be your subdocuments).Then you use regular findOneAndUpdate and replace the subdocument array there.So for example:

const subDocumentsArray = argumentArray?.map((object) => new subDocumentModel(object));const document = await documentModel.findOneAndUpdate(        { _id: id },        { subDocumentsArray },      );