Mongoose 猫鼬方法

Mongoose 猫鼬方法,mongoose,bcrypt,mongoose-schema,Mongoose,Bcrypt,Mongoose Schema,我在我的项目中使用mongoose,在使用UserSchema.pre()函数保存之前对密码进行哈希运算。它工作正常,并加密了密码。但是,当我使用UserSchema.methods.comparePassword时,它会在方法上显示一个错误。方法已声明,但从未使用其值。下面是我正在使用的代码 'use strict'; const mongoose = require('mongoose'); const Schema = mongoose.Schema; const

我在我的项目中使用mongoose,在使用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);

您可以使用.methods
UserSchema.comparePassword
应该可以