Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose instance method is undefined

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: '[email protected]',
  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?

like image 588
user730569 Avatar asked May 23 '12 17:05

user730569


1 Answers

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.

like image 136
user730569 Avatar answered Oct 17 '22 21:10

user730569