Mongoose实例方法未定义 [英] Mongoose instance method is undefined

查看:124
本文介绍了Mongoose实例方法未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  RepSchema.methods.authenticate = function密码){
return this.encryptPassword(password)=== this.hashed_pa​​ssword;
};

在我的应用程序中,我找到rep并调用验证方法:

  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',
密码:XXXXXXXXX,
名称:'meltz',
_id:4fbc6fcb2777fa0272000003 ,
created_at:Wed,23 May 2012 05:04:11 GMT,
confirm:false,
company_head:false}没有方法'authenticate'
解决方案

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


I defined an instance method with Mongoose to authenticate a rep (user):

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

In my app, I find the rep and call the authenticate method on it:

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', {});
  }
});

However I get this error:

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'

What am I doing wrong?

解决方案

So I finally figured out what I was doing wrong. The mongoose source code applies all defined methods inside schema.methods to the prototype of the model at the point at which the model's schema is set to the model name (mongoose.model("modelname", modelSchema)). Therefore, you must define all methods, which adds these methods to the method object of the Schema instance, before you set the model to its name. I was setting the model before defining the methods. Problem solved.

这篇关于Mongoose实例方法未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆