Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose middleware pre update

I am using

schema.pre('save', function (next) {
  if (this.isModified('field')) {
    //do something
  }
});

but I now need to use this same function isModified in a schema.pre('update' hook, but it does not exists. Does anyone know how I can use this same functionality in the update hook?

like image 469
Jeremy Avatar asked Jul 01 '15 23:07

Jeremy


People also ask

What is pre function in Mongoose?

Pre middleware functions are executed one after another, when each middleware calls next . const schema = new Schema(..); schema. pre('save', function(next) { // do stuff next(); }); In mongoose 5. x, instead of calling next() manually, you can use a function that returns a promise.

What is pre hook in Mongoose?

On my journey to explore MongoDB and Mongoose's powerful features over the years, I encountered something called pre and post hooks, few years back. They are simple yet powerful tools with which you can manipulate model instances, queries, perform validation before or after an intended database operation etc.

What is middleware in Mongoose?

Mongoose middleware are functions that can intercept the process of the init , validate , save , and remove instance methods. Middleware are executed at the instance level and have two types: pre middleware and post middleware.

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

Not possible according to this:

Query middleware differs from document middleware in a subtle but important way: in document middleware, this refers to the document being updated. In query middleware, mongoose doesn't necessarily have a reference to the document being updated, so this refers to the query object rather than the document being updated.

update is query middleware and this refers to a query object which has no isModified method.

like image 103
hassansin Avatar answered Sep 16 '22 13:09

hassansin