In mongoose pre middleware, how do i access the update query? In mongoose pre middleware, how do i access the update query? mongoose mongoose

In mongoose pre middleware, how do i access the update query?


I found a work around through this particular example, however it doesnt quite solve my actual problem. what you can do in mongoose version ~4.0.0 is to let the pre middleware specify to go through the model validation on update.

schema.pre('update',function(next){    this.options.runValidators = true; // make sure any changes adhere to schema})

basically, you can then specify the validators inside the schema

var schema = new Schema({    a:{        type:String,        validate:[...] //the validation you want to run    }});

you can choose to skip the validation on a normal save operation by using the this.isNew check inside validation functions.

this code will run validate:[...] on any $set and $unset to a in your update query.

however, it doesn't work on array operations like $push or $addToSet for some reason. so if your updating an array, it won't run the validation code at all! hence it doesn't solve the actual problem im faced with. but it can work with the example provided for anyone that comes across this particular problem


In case you're still looking for a solution that works on array operations, it looks like in newer versions of mongoose (at least 4.0.7+), this._update is defined in the pre-middleware.