Mongoose方法未定义

时间:2015-06-04 16:15:43

标签: node.js mongodb mongoose

我正在尝试为我的用户模型创建一个'checkPassword'方法,但每当我调用它时,我都会收到以下错误:

User.checkPassword(password, hash, function(err, samePassword){
             ^
TypeError: undefined is not a function

我对猫鼬很新,所以我不确定我哪里出错了。

users.js(用户模型)

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);
          }

等。

如果我在console.log用户模型(在passport.js的开头),我可以看到该方法存在,但我无法使用它。我的模型布局类似于文档中的模型布局:http://mongoosejs.com/docs/guide.html(实例方法部分)。

1 个答案:

答案 0 :(得分:10)

您正在声明实例方法(意味着在User模型/类的实例上调用),但您将其称为 class 方法(用Mongoose说法的static method)。

这是一个小型演示:

var mongoose   = require('mongoose');
var testSchema = new mongoose.Schema({ test : String });

testSchema.methods.myFunc = function() {
  console.log('test!');
};

var Test = mongoose.model('Test', testSchema);

// This will fail, because you're calling a class method.
Test.myFunc();

// This will work, because you're calling the method on an instance.
var test = new Test();
test.myFunc();

因此,在您的代码中,您应该将User.checkPassword(...)替换为user.checkPassword(...)(并稍微重写一下),或者使用userSchema.statics.checkPassword = function(...)使其成为正确的类方法。