【问题标题】:Mongoose Methods猫鼬方法
【发布时间】:2018-06-26 04:04:23
【问题描述】:

我在我的项目中使用猫鼬,其中在使用 UserSchema.pre() 函数保存之前对密码进行哈希处理。它工作正常并加密了密码。但是,当我使用 UserSchema.methods.comparePassword 时,它会向我显示方法错误。方法被声明但从未使用过它的值。下面是我正在使用的代码

'use strict';
    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    const bcrypt = require('bcrypt-nodejs');

    const UserSchema = new Schema({
        company_id: String,
        branch_id: String,
        name: String,
        email : String,
        password: String,
    });

    UserSchema.pre('save', function (next) {
        var user = this;
        if(!user.isModified('password')) return next();
        if(user.password) {
            bcrypt.genSalt(10, function(err, salt) {
                if(err) return next(err);
                bcrypt.hash(user.password, salt, null, function(err, hash) {
                    if(err) return next();
                    user.password = hash;
                    next(err)
                })
            })
        }
    });

    UserSchema.methods.comparePassword = function(candidatePassword)  {
        return bcrypt.compareSync(candidatePassword, this.password);
    };

    module.exports = mongoose.model('User', UserSchema);

【问题讨论】:

    标签: mongoose bcrypt mongoose-schema


    【解决方案1】:

    您可以使用 .methods UserSchema.comparePassword 应该没问题

    【讨论】:

      猜你喜欢
      • 2012-09-01
      • 2012-03-21
      • 1970-01-01
      • 2021-10-10
      • 2019-03-25
      • 2018-03-19
      • 2017-10-11
      • 1970-01-01
      • 2014-07-15
      相关资源
      最近更新 更多