简体   繁体   English

findOne 在 LOGIN mongoose node.js 上为空

[英]findOne is null on LOGIN mongoose node.js

//create new user
app.post('/signup', async function(req,res,next) {

    const saltRounds = 10;
    let password = req.body.password;
    let userEmailExist = await user.findOne({ email: req.body.email });

    if(userEmailExist)  return res.status(400).send({ message: "Email already exist" }); ///check if user email already exist
    

    bcrypt.hash(password,saltRounds)
    .then( function(hashedPassword) {
        
    let newUser = new user({
        firstname: req.body.firstname,
        lastname: req.body.lastname,
        email: req.body.email,
        password: hashedPassword
    });
    
    newUser.save(function(error) {
        if(error) throw console.log(error);
        res.send({
            message: 'ok, user is now in db',
            success: true
        })
    });

  });
 
});

//login user
app.post('/login', async function(req,res,next) {
    console.log(req.body.email, req.body.password)

    let userExist = await user.findOne({ email: req.body.email });

    console.log(userExist)

    if(!userExist) return res.status(400).send({
        message: 'Email not found'
    });
    
    let validPassword = await bcrypt.compare(req.body.password, userExist.password, function(err,result) {
        if(err) console.log(err);
    });

});

Hi, above u can find my code where i register user and next try login, but when i search user in collection it return null...but i don't know why.嗨,上面你可以找到我注册用户的代码,然后尝试登录,但是当我在集合中搜索用户时,它返回空...但我不知道为什么。 when i console.log(req.body.email, req.body.password) they exists in my db but my findOne can't search user email and so userExist return null...can anyone help me?当我 console.log(req.body.email, req.body.password) 它们存在于我的数据库中,但我的 findOne 无法搜索用户电子邮件,因此 userExist 返回 null ......有人可以帮助我吗? I'm learning MEVN stack我正在学习 MEVN 堆栈

尝试更改为:

let userExist = await user.findOne({ email: req.body.email }).exec();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM