【问题标题】:Mongoose method undefined猫鼬方法未定义
【发布时间】:2019-11-04 15:01:51
【问题描述】:

我正在尝试为我的用户模型创建一个“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(实例方法部分)。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您正在声明一个 instance 方法(意味着在 User 模型/类的实例上调用),但您将其称为 class 方法(猫鼬用语中的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 有什么偏好吗?
    • @AshleyB 实例方法用于对单个文档执行操作。在您的情况下,checkPassword() 作为实例方法是有意义的,因为您有一个要验证密码的文档 (user)。静态方法主要用于与整个模型/集合相关的操作,例如在其中查找特定文档(链接的 Mongoose 文档中的 Animal.findByName() 就是一个很好的例子)。
    猜你喜欢
    • 2021-01-25
    • 2018-02-05
    • 2019-03-02
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多