In mongoose middleware, how do I access update request?

I am trying to use the new unstable version of mongoose> 4.0.0 to check for update requests.

say i want to update the circuit using the following query

schema.update({_id:'blah'},{a:'blah'},function(err){ //do your thing }) 

so let's say that I have the following diagram,

 var schema = new Schema({ a:{type:String} }); schema.pre('update',function(next){ var findQuery=this._conditions; // gives {_id:'blah'} // how do i get {a:'blah'}???? next(); }); 

How do I get the update request {set: {a: 'blah'}} in the middleware so that I can perform some checks before performing the update?

As an alternative, I know that an update request can be obtained in middleware, in

 schema.post('update',function(){ var findQuery=this._conditions; // gives {_id:'blah'} var updateQuery=this._update; //gives {$set:{a:'blah'}} next(); }); 

but it's too late, I need this in the preliminary middleware to check before actually updating the db.

I tried to view the middleware 'this' object, but cannot find the updateQuery object anywhere and this._update undefined in the middleware.

Is there any way to do this? thanks

+5
source share
2 answers

If you are still looking for a solution that works with array operations, it looks like in the new versions of mongoose (at least 4.0.7+ ), this._update .

+1
source

I found work on this specific example, however this does not completely solve my actual problem. what you can do in mongoose ~ 4.0.0 is to let the pre-middleware skip model validation when upgrading.

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

in principle, you can specify validators inside the circuit

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

you can skip validation in a normal save operation using the this.isNew function inside the validation functions.

this code will run a check: [...] for any $ set and $ unset for a in your update request.

however, for some reason, it does not work on array operations such as $ push or $ addToSet. therefore, if you update the array, it will not run the verification code at all! therefore, it does not solve the actual problem that it is facing. but he can work with an example provided to all who are faced with this particular problem.

0
source

All Articles