2017-02-17 48 views
2

我有一个应用程序的NodeJS这猫鼬模式:为什么我不能访问猫鼬模式的方法?

const mongoose = require('mongoose'), 
    Schema = mongoose.Schema, 
    sodium = require('sodium').api; 

const UserSchema = new Schema({ 
    username: { 
     type: String, 
     required: true, 
     index: { unique: true } 
    }, 
    salt: { 
     type: String, 
     required: false 
    }, 
    password: { 
     type: String, 
     required: true 
    } 
}); 

UserSchema.methods.comparePassword = function(candidatePassword, targetUser) { 
    let saltedCandidate = candidatePassword + targetUser.salt; 
    if (sodium.crypto_pwhash_str_verify(saltedCandidate, targetUser.password)) { 
     return true; 
    }; 
    return false; 
}; 

module.exports = mongoose.model('User', UserSchema); 

而且我创造了这个路线文件。

const _ = require('lodash'); 
const User = require('../models/user.js'); // yes, this is the correct location 

module.exports = function(app) { 
    app.post('/user/isvalid', function(req, res) { 
     User.find({ username: req.body.username }, function(err, user) { 
      if (err) { 
       res.json({ info: 'that user name or password is invalid. Maybe both.' }); 
      }; 
      if (user) { 
       if (User.comparePassword(req.body.password, user)) { 
        // user login 
        res.json({ info: 'login successful' }); 
       }; 
       // login fail 
       res.json({ info: 'that user name or password is invalid Maybe both.' }); 
      } else { 
       res.json({ info: 'that user name or password is invalid. Maybe both.' }); 
      }; 
     }); 
    }); 
}; 

然后,我使用邮递员拨打127.0.0.1:3001/user/isvalid与适当的身体内容。终端说告诉我TypeError: User.comparePassword is not a function并崩溃的应用程序。

由于if (user)位通过,这表明我已经从Mongo中正确检索了一个文档并拥有User模式的实例。为什么该方法无效?

ETA:模块出口我无法复制/粘贴最初

+1

添加到最终用户模型模块的:'module.exports = mongoose.model( '用户',UserSchema);' – dNitro

+0

@dNitro我未能复制/粘贴,但它在我的实际代码。接得好。编辑添加它 –

回答

4

这将创建实例方法:

UserSchema.methods.comparePassword = function(candidatePassword, targetUser) { 
    // ... 
}; 

如果你想有一个静态方法使用这样的:

UserSchema.statics.comparePassword = function(candidatePassword, targetUser) { 
    // ... 
}; 

静态方法当你想把它称为User.comparePassword()

实例方法是当你想把它称为someUser.comparePassword()(在这种情况下会产生很多意义,这样你就不必显式地传递用户实例)。

参见文档:

+0

因此给出我提供的代码,传递'(用户)'应该意味着'user.comparePassword()'应该工作,但它会给出相同的错误。 保持原样并在模式定义中使用'UserSchema.statics.comparePassword'确实可行,所以我并不怀疑它。我猜,我只是感到困惑。 –

相关问题