Mongoose Middleware Pre-Update

I use

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

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

+6
source share
4 answers

Impossible according to this :

The middleware tool differs from the middleware of the document in a subtle but important way: in the middleware document this refers to the document being updated. In the mongoose query middleware, a link to an updated document is not necessary, therefore this refers to a query object, not an updated document.

update is the request middleware, and this refers to a request object that does not have an isModified method.

+10
source

@ Jeremy, I came to the same problem and finally found a workaround:

 schema.pre('update', function(next) { const modifiedField = this.getUpdate().$set.field; if (!modifiedField) { return next(); } try { const newFiedValue = // do whatever... this.getUpdate().$set.field = newFieldValue; next(); } catch (error) { return next(error); } }); 

Taken from here: https://github.com/Automattic/mongoose/issues/4575

In doing so, you can check whether any update is coming in the field, but you cannot check whether the input value is different from the saved one. It works great for my use case (password encryption after reset)

I hope this helps.

+5
source
 Schema.pre('updateOne', function (next) { const data = this.getUpdate() data.password = 'Teste Middleware' this.update({}, data).exec() next() }) const user = await User.updateOne({ _id: req.params.id }, req.body) 

it worked for me

0
source

I recently came across this github post and found a working update. Here it is.

 schema.pre('findOneAndUpdate', function() { this.findOneAndUpdate({}, { $set: { updatedAt: new Date() } }); }); 
-3
source

Source: https://habr.com/ru/post/1210352/


All Articles