Mongoose instance method is undefined

假如想象 提交于 2019-12-18 16:10:09

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10724876/mongoose-instance-method-is-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!