I would prevent any sub document from being removed, thus I added an error to the pre('remove') middleware of each sub document Schema.
When calling the .remove() function, it effectively calls the middleware. But when it is deleted without calling remove(), the middleware doesn't check if it has been removed.
The cases where is matters is when I receive an object from a remote source, I'd like to perform all the integrity checks via mongoose middlewares to keep everything at the same place. The remote source can have, by mistake or not, deleted one of the sub docs. So when Mongoose is checking the whole doc, the sub doc has already been removed without triggering the .remove() function.
Here is the minimal working example of my problem:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var subDateSchema = new Schema({
date_add: {type: Date, default: Date.now},
date_remove: {type: Date, default: null}
});
var ResourceSchema = new Schema({
activation_dates: [subDateSchema]
});
subDateSchema.pre('remove', function(next){
next(new Error("YOU CAN'T DELETE ANY ACTIVATION DATE"));
});
var Resource = mongoose.model('Resource', ResourceSchema);
var newresource = new Resource({
activation_dates: [{
date_add: Date.now()
}]
});
newresource.save(function(err){
if(err) throw err;
newresource.activation_dates.splice(0, 1);
/**
* Here I tried
* newresource.markModified('activation_dates');
* On update it *DOES* trigger pre save and pre validate
* But it does nothing to deleted content
**/
newresource.save(function(err){
if(err) throw err;
});
});
So my question is: Is there a clean way to call sub doc removing middleware without proceeding to check for all the previous elements and compare with the new ones to see which ones are being deleted ?
After a little bit of researches, I found this:
A workaround can be to hook an event to the whole array of Sub Documents, and to have a copy of the previous array of data.
This is a complete working example on how to be sure an array element hasn't been deleted or pulled out. To check for modifications, you'll need further modifications.
Unfortunately I couldn't find another solution than doing a loop over all elements and retrieving the original document.