【发布时间】:2020-01-10 11:10:35
【问题描述】:
我正在制作一个需要登录系统的全栈网站当用户注册他的数据成功插入数据库时,我正在使用 mongoose 将我的项目与 mongodb 连接起来,问题是登录时我尝试查找已注册的电子邮件始终以未找到用户的方式回复。
我正在尝试检查用户是否已注册,以便我可以让他能够登录,但即使他已注册,它也总是以 null 响应。
这是我尝试登录但总是以未找到用户的方式响应:
路由器代码:
router.post("/login", (req, res) => {
const email = req.body.email;
const password = req.body.password;
// the problem is here in the findOne function
User.findOne({ email:email }).then(user => {
if (!user) {
return res.status(404).json({ email: "User not found" });
}
bcrypt.compare(password, user.password).then(isMatch => {
if (isMatch) {
res.json({ msg: "Success" });
} else {
return res.status(400).json({ password: "password incorrect" });
}
});
});
});
架构代码:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
avatar: {
type: String
},
date: {
type: Date,
default: Date.now
}
});
module.exports = User = mongoose.model("users", UserSchema);
【问题讨论】:
-
如果您删除
bcrypt.compare(password, user.password)部分,并在成功时删除return user,它会在您的情况下正常工作吗?user是否通过email字段找到了自己,他存在吗? -
感谢您的回答,但没有,因为他不能只使用电子邮件登录,代码的问题是即使找到了电子邮件,它也没有进入下一步检查密码是否正确
-
用户通过他的电子邮件被检查是否被找到,所以如果他没有找到它说用户没有找到但是如果他被找到然后他检查密码是否正确如果它不正确然后它说密码不正确
-
我理解了你代码的逻辑,我说如果你删除
bcryct通过哈希密码检查,findOne方法是否可以通过电子邮件正确找到用户?只需回复我:“是或否”。并在您发表下一条评论时尝试使用逗号。 -
不,它给了我同样的“找不到用户”
标签: node.js mongodb express mongoose mongodb-atlas