【发布时间】:2017-07-07 06:23:21
【问题描述】:
我在 Nodejs 应用程序中有这个 Mongoose 模式:
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.' });
};
});
});
};
然后我使用 Postman 使用适当的 Body 内容调用 127.0.0.1:3001/user/isvalid。终端说告诉我TypeError: User.comparePassword is not a function 并让应用程序崩溃。
自从if (user) 位通过以来,这表明我已经从 Mongo 正确检索了一个文档并拥有一个 User 模式的实例。为什么方法无效?
eta:我原来复制/粘贴失败的模块导出
【问题讨论】:
-
添加到用户模型模块的末尾:
module.exports = mongoose.model('User', UserSchema); -
@dNitro 我无法复制/粘贴它,但它在我的实际代码中。接得好。编辑添加它
标签: node.js mongoose mongoose-populate