Javascript Mongoose对于保存和更新中间件具有相同的功能
所以我有一个问题:如何让中间件在两个不同的钩子上运行? 我要替换此代码:Javascript Mongoose对于保存和更新中间件具有相同的功能,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,所以我有一个问题:如何让中间件在两个不同的钩子上运行? 我要替换此代码: userSchema.pre('save', function(next) { if (!this.localAuth.password) next(); this.localAuth.password = this.generateHash(this.localAuth.password); next(); }) userSchema.pre('update', function(next) { if (
userSchema.pre('save', function(next) {
if (!this.localAuth.password) next();
this.localAuth.password = this.generateHash(this.localAuth.password);
next();
})
userSchema.pre('update', function(next) {
if (!this.localAuth.password) next();
this.localAuth.password = this.generateHash(this.localAuth.password);
next();
})
比如说:
userSchema.pre('saveOrUpdate', function(next) {
if (!this.localAuth.password) next();
this.localAuth.password = this.generateHash(this.localAuth.password);
next();
})
注意这些函数是如何相同的,我只需要一个运行在save和update上的钩子。感谢您的帮助。谢谢 您可以创建一个单独的身份验证函数,然后从两个钩子调用它
function auth ( next ) {
//do stuff here
if (!this.localAuth.password) next();
this.localAuth.password = this.generateHash(this.localAuth.password);
next();
}
//for save operation
userSchema.pre("save", auth);
//update operation
userSchema.pre("update", auth);
您可以为身份验证创建一个单独的函数,然后从两个钩子调用它
function auth ( next ) {
//do stuff here
if (!this.localAuth.password) next();
this.localAuth.password = this.generateHash(this.localAuth.password);
next();
}
//for save operation
userSchema.pre("save", auth);
//update operation
userSchema.pre("update", auth);
可用中间件:可用中间件: