非常感谢使用MongoDB和Node。如果请求正文中的电子邮件与数据库中的电子邮件匹配,我想从文档中返回两个字段。这是我现在所拥有的:
router.post('/login', async (req, res) => {
//console.log(req.body);
const user = User.collection.find({username: req.body.username}, {username: 1, password: 1});
console.log(user);
if(user == null) {
return res.status(400).json({ message: 'Cannot find user with that username' });
}
try {
if(await bcrypt.compare(req.body.password, user.password)) {
res.status(201).json(user)
} else {
res.status(400).json({ authenticated: false })
}
} catch (err) {
res.status(500).json({ message: err })
}
});
我认为user.password是未定义的,因此它会触发catch调用并返回状态500。
我的输出console.log(user)
返回一个游标对象,其中包含一堆数据。在光标对象中,有一个选项对象,它显示了我传递的选项{用户名:1,密码:1}。还有一个cmd对象,其查询字段的值为{username:'GivenUsername'}
在任何输出中都没有看到我要查询的数据。我究竟做错了什么?
collection.find()
返回一个游标。您可以使用其next()
方法来获取单个文档(不要忘记检查hasNext()
是否需要),也可以使用方法toArray()
一次获取所有文档。
PS不会忘记您需要return
在if/else/catch
块中回应。
更新:您应该像这样使用它:
const cursor = User.collection.find({username: req.body.username}, {username: 1, password: 1});
if(!(await cursor.hasNext())) {
return res.status(400).json({ message: 'Cannot find user with that username' });
}
const user = await cursor.next();
try {
if(await bcrypt.compare(req.body.password, user.password)) {
return res.status(201).json(user)
} else {
return res.status(400).json({ authenticated: false })
}
} catch (err) {
return res.status(500).json({ message: err })
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句