【问题标题】:Issue with `this` using mongoose methods使用猫鼬方法的“this”问题
【发布时间】: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


    【解决方案1】:

    好的,我找到了问题。
    永远不要说得太快,问题来自 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')
    

    【讨论】:

      猜你喜欢
      • 2021-10-10
      • 2021-04-09
      • 1970-01-01
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 2021-01-03
      • 2018-03-04
      相关资源
      最近更新 更多