[英]How to reuse a pre middleware function in mongoose
I need to reuse one of pre middleware functions in another pre middleware, for that I extracted a function like so:我需要在另一个预中间件中重用一个预中间件函数,为此我提取了一个函数,如下所示:
async function encryptPassword(next) {
if (!this.isModified('password')) {
return next();
}
this.password = await bcrypt.hash(this.password, 5);
this.passwordChangedAt = new Date();
next();
}
UserSchema.pre('save', encryptPassword);
UserSchema.pre("findOneAndUpdate", encryptPassword);
But I am getting an error saying that this.isModified
is not a function, I assume that this
is referring to something else.但是我收到一个错误,说
this.isModified
不是一个函数,我认为this
是指其他东西。 How to fix this?如何解决这个问题?
I dived into these pre/post hooks with a help of debugger & docs and I have found several things (these apply to both pre
and post
):我在调试器和文档的帮助下深入研究了这些 pre/post 钩子,我发现了几件事(这些适用于
pre
和post
):
Using save
hook will mean that this
refers a document itself.使用
save
钩子意味着this
指的是一个文档本身。 Thus, you can update its fields, call methods like isModified
, etc. You should not have any issues with the above method.因此,您可以更新其字段,调用
isModified
等方法。使用上述方法应该不会有任何问题。
However, findOneAndUpdate
hook will mean that this
refers to a query instead of document.但是,
findOneAndUpdate
钩子将意味着this
指的是查询而不是文档。 And Query object will not have documents or their inherited methods (like isModified
).并且 Query 对象不会有文档或其继承的方法(如
isModified
)。
I checked with debugger and can confirm it is the case (up-to-date with documentation).我检查了调试器并可以确认是这种情况(最新的文档)。
A list of hooks:https://mongoosejs.com/docs/middleware.html#types-of-middleware钩子列表:https ://mongoosejs.com/docs/middleware.html#types-of-middleware
You will see that only the following hooks allow to modify documents:您将看到只有以下钩子允许修改文档:
validate
save
remove
updateOne
deleteOne
init (note: init hooks are synchronous)
And all others will not.而所有其他人都不会。 It seems this is intentional ( https://github.com/Automattic/mongoose/issues/964 ).
这似乎是故意的( https://github.com/Automattic/mongoose/issues/964 )。
To solve an issue with findOneAndUpdate
, it seems the only way (most closely resembling) is to rework to findOne
and updateOne
as separate queries.为了解决
findOneAndUpdate
的问题,似乎唯一的方法(最相似)是将findOne
和updateOne
作为单独的查询进行返工。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.