【问题标题】:method is not a function Mongoose methods problem方法不是函数猫鼬方法问题
【发布时间】:2021-04-09 14:33:22
【问题描述】:

环境:

节点 v12.19.0

mongo Atlas V4.2.11

猫鼬 V5.11.8

##############################################

我有一个用户架构

user.js

const mongoose = require('mongoose');
const bcrypt   = require('bcrypt');

const userSchema = new mongoose.Schema({
    email:{
        type: String,
        required: true,
        unique: true, 
    },
    username:{
        type: String,
        required: true,
        unique: true,
    },
    password:{
        type: String,
        required: true
    },
    profileImageUrl:{
        type: String,
    }
});

userSchema.pre('save', async function(next) {
    try{
        if(!this.isModified('password')){
            return next();
        }

        let hashedPassword = await bcrypt.hash(this.password, 10);
        this.password = hashedPassword;
        return next();

    } catch(err) {
        return next(err);
    }
});

userSchema.methods.comparePassword = async function(candidatePassword){
    try{
        return await bcrypt.compare(candidatePassword, this.password);

    } catch(err){
        throw new Error(err.message);
    }
}

userSchema.set('timestamps', true);

module.exports = mongoose.model("User", userSchema);

我正在检查密码是否没有被修改,然后我在保存前修改它。

我添加了一个方法来将密码与散列密码进行比较,称为 comparePassword

我正在尝试在另一个文件中使用 comparePassword 方法

Auth.js


const db = require('../models');
const JWT = require("jsonwebtoken");
const CONFIGS = require('../config');

exports.signIn = async function(req, res, next){
    try{

        const user = db.User.findOne({
            email: req.body.email,
        });

        const { id, username, profileImageUrl } = user;
        const isMatch = await user.comparePassword(req.body.password) ; // here is a problem <====

        if(isMatch){
            const token = JWT.sign({
                id,
                username,
                profileImageUrl,
            }, CONFIGS.SECRET_KEY);
            return res.status(200).json({
                id,
                username,
                profileImageUrl,
                token,
            });
        }
        else{
            return next({
                status: 400,
                message: "Invalid email or password",
            });
        }
    }
    catch(err){
        return next(err);
    }
}
   

当我尝试将密码与预定义的方法进行比较时,它会在响应中返回这个

user.comparePassword 不是函数

我查看了各种解决方案。

有人说这对他们有用:

userSchema.method('comparePassword' , async function(candidatePassword, next){
  // the logic
})

但它不起作用我也尝试了不同的解决方案,但我不确定代码有什么问题。

更新 1:

我尝试使用静态,但它不起作用

userSchema.statics.comparePassword = async function(candidatePassword){
    try{
        return await bcrypt.compare(candidatePassword, this.password);

    } catch(err){
        throw new Error(err.message);
    }
}

【问题讨论】:

标签: javascript node.js mongodb mongoose


【解决方案1】:

Auth.js

 const user = db.User.findOne({
            email: req.body.email,
        });

这是错误的,因为我们必须等待查询完成;

应该是这样的

 const user = await db.User.findOne({
            email: req.body.email,
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-10
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 2020-02-28
    • 2023-01-05
    相关资源
    最近更新 更多