user730569
user730569

Reputation: 4004

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?

Upvotes: 9

Views: 4905

Answers (1)

user730569
user730569

Reputation: 4004

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.

Upvotes: 16

Related Questions