Mongoose实例方法未定义

use*_*569 9 instance mongoose mongodb node.js express

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

RepSchema.methods.authenticate = function(password){
  return this.encryptPassword(password) === this.hashed_password;
};
Run Code Online (Sandbox Code Playgroud)

在我的应用程序中,我找到代表并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', {});
  }
});
Run Code Online (Sandbox Code Playgroud)

但是我收到此错误:

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'
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

use*_*569 16

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