node.js - Mongoose method undefined -


i'm trying create 'checkpassword' method user model, whenever call following error:

user.checkpassword(password, hash, function(err, samepassword){              ^ typeerror: undefined not function 

i'm pretty new mongoose i'm not sure i'm going wrong.

users.js (user model)

var mongoose = require('mongoose'), schema = mongoose.schema, bcrypt = require('bcrypt');   var userschema = new schema({  email : {type: string, required: true, unique: true},  password : {type: string, required: true},  firstname : {type: string},  lastname : {type: string} });   userschema.methods.checkpassword = function checkpassword(password, hash, done){      bcrypt.compare(password, hash, function(err, samepassword) {       if(samepassword === true){         done(null, true);       } else {         done(null, false)       }     }); }  module.exports = mongoose.model('user', userschema); 

passport.js

var passport = require('passport'),     localstrategy = require('passport-local').strategy,     mongoose = require('mongoose'),     usersmodel = require('../models/users'),     user = mongoose.model('user');   passport.use(new localstrategy({     usernamefield: 'email',     passwordfield: 'password'   }, function(email, password, done){      user.findone({'email': email}, function(err, user){       if(user){          var hash = user.password;         user.checkpassword(password, hash, function(err, samepassword){           if(samepassword === true){             done(null, user);           } 

etc..

if console.log user model (at start of passport.js), can see method there, i'm unable use it. model layout similar 1 in documentation: http://mongoosejs.com/docs/guide.html (instance methods section).

you're declaring instance method (meant called on instances of user model/class) you're calling class method (a static method in mongoose parlance).

here's small demonstration:

var mongoose   = require('mongoose'); var testschema = new mongoose.schema({ test : string });  testschema.methods.myfunc = function() {   console.log('test!'); };  var test = mongoose.model('test', testschema);  // fail, because you're calling class method. test.myfunc();  // work, because you're calling method on instance. var test = new test(); test.myfunc(); 

so in code, should either replace user.checkpassword(...) user.checkpassword(...) (and rewrite bit), or make proper class method using userschema.statics.checkpassword = function(...).


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -