Mongoose方法未定义。

4

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

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

我是一个新手,对mongoose不太熟悉,所以不确定我的问题出在哪里。

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

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

1个回答

12
你正在声明一个实例方法(旨在调用User模型/类的实例),但你将其作为类方法(在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(...)将其变成一个恰当的类方法。


谢谢提供的示例 - 真的很容易理解。将其更改为'userSchema.statics.checkPassword'就可以了。我是否有偏好,想要使用{modelSchema}.methods还是{modelSchema}.statics? - Ash
2
@AshleyB 实例方法用于针对单个文档执行操作。在您的情况下,checkPassword() 会作为一个实例方法有意义,因为您有一个要验证密码的单个文档(user)。静态方法主要用于涉及整个模型/集合的操作,例如查找其中特定的文档(链接的 Mongoose 文档中的 Animal.findByName() 就是一个很好的例子)。 - robertklep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接