我有一個應用程序的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:模塊出口我無法複製/粘貼最初
添加到最終用戶模型模塊的:'module.exports = mongoose.model( '用戶',UserSchema);' – dNitro
@dNitro我未能複製/粘貼,但它在我的實際代碼。接得好。編輯添加它 –