使用猫鼬方法处理"this"问题




我现在遇到了一个问题
当我在Mongoose的方法中使用关键字this时,它会返回一个undefined值,而对于pre方法,我会得到所需的值。我使用bcrypt-nodejs和mongose来运行这个文件。我不认为问题来自于我在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);

好的,我发现了问题
永远不要说得太快,问题来自API
事实上,在选择时,我删除了密码,所以它找不到。愚蠢的错误,我的错。,我以前有过这个

loginRouter.post('/', (req, res) => {
Staff.findOne({ email: req.body.email })
.select('firstname lastname username email type')

现在解决方法是:

loginRouter.post('/', (req, res) => {
Staff.findOne({ email: req.body.email })
.select('firstname lastname username password email type')

相关内容

最新更新