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?