方法不是函数猫鼬方法问题
Posted
技术标签:
【中文标题】方法不是函数猫鼬方法问题【英文标题】: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);
【问题讨论】:
你可以试试statics
吗? ***.com/questions/39708841/…
是的,我尝试使用静态
【参考方案1】:
在 Auth.js
const user = db.User.findOne(
email: req.body.email,
);
这是错误的,因为我们必须等待查询完成;
应该是这样的
const user = await db.User.findOne(
email: req.body.email,
);
【讨论】:
以上是关于方法不是函数猫鼬方法问题的主要内容,如果未能解决你的问题,请参考以下文章
变异时如何修复“猫鼬模型的名称”不是graphql中的构造函数
在猫鼬中进行预更新时,user.isModified 不是函数
错误:TypeError:user.insertOne 不是使用猫鼬的函数