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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With