任何人都可以弄清楚下面我的代码有什么问题吗?
从文档中看起来this,Mongoose .pre('save')方法应该是模型本身,但在下面的代码中this最终成为一个空对象.
const Mongoose = require('./lib/database').Mongoose;
const Bcrypt = require('bcrypt');
const userSchema = new Mongoose.Schema({
email: { type: String, required: true, index: { unique: true } },
password: { type: String, required: true }
});
userSchema.pre('save', (next) => {
const user = this;
Bcrypt.genSalt((err, salt) => {
if (err) {
return next(err);
}
Bcrypt.hash(user.password, salt, (err, encrypted) => {
if (err) {
return next(err);
}
user.password = encrypted;
next();
});
});
});
const User …Run Code Online (Sandbox Code Playgroud)