Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 872
JasonY Avatar asked May 23 '15 05:05

JasonY


People also ask

How do I update my mongoose?

There are multiple ways to update documents in Mongoose. You can either use the save() , updateOne() , updateMany() , or findOneAndUpdate() method.

What is pre function in mongoose?

Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plugins.

What are pre and post hooks?

Pre- and post-execution hooks are Processing scripts that run before and after actual data processing is performed. This can be used to automate tasks that should be performed whenever an algorithm is executed.


1 Answers

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.

like image 128
dbrianj Avatar answered Oct 10 '22 14:10

dbrianj