Mongoose: How to replace an array of subdocuments?

I created a custom schema with mongoose that contains the contacts subdocument. The “contacts” subdocument is a set of contact objects that contain the actual contact (link to another user object) and some data related to “friendship”.

In my external application, I can now manage contacts by adding or removing users to my contact list. The external interface saves these changes as HTTP PUT requests to the server.

The PUT request contains the entire user object, which more or less replaces the user object in the database. Unfortunately, it is not possible to replace the subdocument assembly. You can only click new or delete them.

Here are the diagrams:

var UserSchema = new Mongoose.Schema({ username: { type: String, index: { unique: true, sparse: true }, required: true, lowercase: true, trim: true }, email: { type: String, index: { unique: true, sparse: true }, required: true, lowercase: true, trim: true }, contacts: [ContactSchema] }); var ContactSchema = new Mongoose.Schema({ user: { ref: "User", type: Mongoose.Schema.ObjectId }, isContact: { type: Boolean, default: true } }); 

I am currently trying to replace contacts by deleting all and adding them to the request:

 app.put('/me', loadUser, function(req, res, next) { var user = req.user; req.user.contacts.forEach(function(contact) { req.body.contacts.forEach(function(contact) { contact.remove(); }); }); req.body.contacts.forEach(function(contact) { req.user.contacts.push(contact); }); user.save(function(err, user) { if (err) return next(err); res.send(200); }); }); 

Does anyone really know better how I can update this collection of subdocument to state in request?

+4
source share
1 answer

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

Here is an example of 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; }) 

Expected Result:

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

If you know the identifier, even better.

All you have to do is remove your pallets by following these steps:

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

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

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

save and do.

Hope this helps.

Just a hint, in mongodb you are working with object arrays, you can simply replace each value:

 // active data from database user.name = 'test user'; // now just give the object a new value user.name = 'new name'; // and save .. done user.save(); 
+4
source

Source: https://habr.com/ru/post/1446740/


All Articles