gpt4 book ai didi

node.js - Mongoose 实例方法未定义

转载 作者:IT老高 更新时间:2023-10-28 23:24:04 24 4
gpt4 key购买 nike

我用 Mongoose 定义了一个实例方法来验证代表(用户):

RepSchema.methods.authenticate = function(password){
return this.encryptPassword(password) === this.hashed_password;
};

在我的应用程序中,我找到了代表并对其调用 authenticate 方法:

var mongoose = require("mongoose");
var Rep = mongoose.model("Rep");

Rep.findOne({email: email}, function(err, rep){
if (rep.authenticate(req.body.session.password)){
req.session.rep_id = rep._id;
res.redirect('/calls', {});
}
});

但是我得到了这个错误:

TypeError: Object { email: 'meltzerj@wharton.upenn.edu',
password: XXXXXXXXX,
name: 'meltz',
_id: 4fbc6fcb2777fa0272000003,
created_at: Wed, 23 May 2012 05:04:11 GMT,
confirmed: false,
company_head: false } has no method 'authenticate'

我做错了什么?

最佳答案

所以我终于弄清楚我做错了什么。 mongoose 源代码将 schema.methods 中定义的所有方法应用于模型的原型(prototype),在该点将模型的模式设置为模型名称 (mongoose.model("modelname", modelSchema))。因此,在将模型设置为其名称之前,您必须定义所有方法,将这些方法添加到 Schema 实例的方法对象中。我在定义方法之前设置了模型。问题解决了。

关于node.js - Mongoose 实例方法未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10724876/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com