【发布时间】:2018-12-30 15:39:13
【问题描述】:
我现在遇到了问题。
当我在 Mongoose 的方法中使用关键字 this 时,它会返回一个 undefined 值,而对于 pre 方法,我会得到询问的值。
我正在使用 bcrypt-nodejs 和 mongoose 运行此文件。我认为问题不在于我在 API 上调用它的方式,因为它在到达方法之前就找到了正确的方式。
这是代码:
const mongoose = require('mongoose');
const bcrypt = require('bcrypt-nodejs');
const Schema = mongoose.Schema;
const StaffSchema = new Schema({
firstname: {type: String, required: true},
lastname: {type: String, required: true},
username: {type: String, required: true, unique: true},
email: {type: String, required: true, unique: true},
password: {type: String, required: true},
type: {type: String, required: true},
});
StaffSchema.pre('save', function(next) {
let staff = this;
console.log(staff);
if (!staff.isModified('password')) {
return next();
}
bcrypt.hash(staff.password, null, null, (err, hash) => {
if (err) return next(err);
staff.password = hash;
next();
});
});
StaffSchema.methods.comparePasswords = function(password) {
console.log(password, this.password);
if(this.password != null) {
return bcrypt.compareSync(password, this.password);
} else {
return false;
}
};
module.exports = mongoose.model('Staff', StaffSchema);
【问题讨论】:
标签: node.js mongoose mongoose-schema