6

I am trying to use the new unstable version of mongoose >4.0.0 to validate update queries.

say that i want to update a schema using the following query

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

so lets say i have the following schema,

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 query of {set:{a:'blah'}} in the pre middleware so i can do some checks before executing the update?

alternatively i know that the update query can be accessed in the post middleware, in

schema.post('update',function(){
var findQuery=this._conditions;  // gives {_id:'blah'}

var updateQuery=this._update; //gives {$set:{a:'blah'}}

next();
});

but thats too late, i need this in the pre middleware to check before actually updating the db.

i tried looking through the 'this' object of the pre middleware but cannot find the updateQuery object anywhere and this._update is undefined in the pre middleware.

Is there a way to do this? thanks

JasonY
  • 752
  • 10
  • 24

2 Answers2

1

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

JasonY
  • 752
  • 10
  • 24
1

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.

dbrianj
  • 440
  • 4
  • 10