【发布时间】:2018-05-07 05:23:33
【问题描述】:
用户在数据库中创建,检查了几次代码,没有语法错误,只是返回未定义,即使用户被创建。使用名称和密码进行发布请求时,请正确输入凭据。代码:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var User = new Schema({
name: String,
password: String,
admin: Boolean
});
var Usermodel = mongoose.model("user", User);
module.exports = Usermodel;
router.post('/authenticate', function(req, res) {
// find the user
user.findOne({
name: req.body.name
}).then(function(err, user) {
console.log(user);
if (err) throw err;
if (!user) {
res.json({ success: false, message: 'Authentication failed. User not found.' });
} else if (user) {
// check if password matches
if (user.password != req.body.password) {
res.json({ success: false, message: 'Authentication failed. Wrong password.' });
} else {
// if user is found and password is right
// create a token with only our given payload
// we don't want to pass in the entire user since that has the password
const payload = {
admin: user.admin
};
var token = jwt.sign(payload, 'superSecret', {
expiresIn: 60*60*24 // expires in 24 hours
});
// return the information including token as JSON
res.json({
success: true,
message: 'Enjoy your token!',
token: token
});
}
}
});
});
需要所有依赖项,我没有在控制台收到任何错误,只是 if 语句没有找到我创建的用户,并且 console.log 返回未定义。我在这里想念什么吗?这没有任何意义。我将回调更改为承诺,但仍然相同。在数据库中寻找用户时,我觉得我做错了什么。我试过 find({}) 但没有运气。
【问题讨论】:
-
你能从 mongo 控制台找到吗?
-
在基于 promise 的 mongoose findOne 中,您只能在 then 子句中获得文档。我还建议使用 exec()。
-
@MustafaMamun 我正在使用 Robo 3T 作为 mongo 控制台的替代品,但是是的,我也可以在控制台中看到它。
-
@tumulr 我到底需要在哪里使用它?
-
@Limpuls 检查此mongoosejs.com/docs/promises.html