Mongoose实例方法未定义
我使用Mongoose定义了一个实例方法来validation代表(用户):
RepSchema.methods.authenticate = function(password){ return this.encryptPassword(password) === this.hashed_password; };
在我的应用程序中,我find了代表并调用它的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'
我究竟做错了什么?
所以我终于明白我在做什么错了。 schema.methods
源代码将schema.methods
中的所有已定义方法应用于模型模式设置为模型名称( mongoose.model("modelname", modelSchema)
)处模型的原型。 因此,在将模型设置为名称之前,必须定义所有方法,这些方法将这些方法添加到模式实例的方法对象中。 在定义方法之前,我正在设置模型。 问题解决了。