有人能帮我找出下面代码的问题吗?
从文档来看,Mongoose的.pre('save')
方法中的this
应该是模型本身,但在我的代码中,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 = Mongoose.model('User', userSchema);
保存用户时,我遇到了以下错误:
[错误:需要数据和salt参数]
。function createUser(email, password, next) {
const user = new User({
email: email,
password: password
});
user.save((err) => {
if (err) {
return next(err);
}
return next(null, user);
});
}
createUser('test@email.com', 'testpassword', (err, user) => {
if (err) {
console.log(err);
}
else {
console.log(user);
}
process.exit();
});
如果我移除.pre('save')
,那么它当然可以正常保存了。我使用的Mongoose版本是4.2.6。
const
?请改用var
,然后在预处理脚本中使用this
指代记录而不是模型。 - michelemconst
,因为这些变量从不改变。 我尝试更改为var
,代码运行相同。 - jawang35