Mongoose实例方法未定义。

9
我使用Mongoose定义了一个实例方法,用于认证一个代表(用户):

我使用Mongoose定义了一个实例方法,用于认证一个代表(用户):

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

在我的应用程序中,我找到了rep并调用了其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'

我做错了什么?


@JohnnyHK 不确定我会省略哪些相关代码。 - user730569
@JohnnyHK 即使我通过 rep = new Rep(); 实例化一个全新的对象,当我调用 authenticate 时它仍然会抛出相同的错误。 - user730569
1个回答

16

所以,我终于找出了自己做错的地方。Mongoose源代码在将模式设置为模型名称(mongoose.model(“modelname”,modelSchema))时,在模型的原型中应用schema.methods中定义的所有方法。因此,在将模型设置为其名称之前,必须定义所有方法,这将添加这些方法到Schema实例的方法对象中。我是在定义方法之前设置模型的。问题解决。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接