【发布时间】:2016-02-19 20:36:55
【问题描述】:
谁能弄清楚我下面的代码有什么问题?
从文档看来,Mongoose 中的 this .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 = Mongoose.model('User', userSchema);
保存用户时,我收到以下错误[Error: data and salt arguments required]。
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。 -
我正在使用
const,因为这些变量永远不会改变。我尝试更改为var并且代码运行相同。
标签: javascript node.js mongodb mongoose ecmascript-6