Search code examples
node.jsmongodbexpressmongoosesession

Unable to get document using document.findOne()


I tried to get a document using document.findOne() but it's value is showing undefined . Here is my code `app.post("/studentlogin",(req,res)=> {

let password;
console.log("login page");
bcrypt.hash(req.body.password,saltRounds,(err,hash)=>
{
      const user= Student.findOne({srno:req.body.srno});
      console.log(user.srno);
    if(req.body.srno==user.srno && hash==user.password)
    {
        session=req.username;
        session.userid=req.body.srno;
        res.redirect("/");
    }
    else{
        console.log("invalid user");
        res.redirect("/studentlogin");
    }
});

})`

I'm implementing session authentication using express-session. Here when I log the user it's showing schema and bunch of other stuff which I don't know(The error is too long) . user.srno is also showing as undefined. How can I fix it?

I tried using call-back function which gave me required document correctly. But I want the query to return the correct document and store it in user. Using callback function `app.post("/studentlogin",(req,res)=> {

let password;
console.log("login page");
bcrypt.hash(req.body.password,saltRounds,(err,hash)=>
{
      Student.findOne({srno:req.body.srno},(err,result)=>
    {
        console.log(result);
    });
    //console.log(user.srno);
    if(req.body.srno==user.srno && hash==user.password)
    {
        session=req.username;
        session.userid=req.body.srno;
        res.redirect("/");
    }
    else{
        console.log("invalid user");
        res.redirect("/studentlogin");
    }
});

})`


Solution

  • You need to wait the result from your query on the database before doing the next task like comparing your password, and looks like you just try to log in, you re not going to register a new one, so it's better to use the compare method in Bcrypt like this :

    app.post("/studentlogin", async (req , res) => {
        const {srno, password} = req.body  // destructuring your request is better for visibility
    try {
        const user = await Student.findOne({srno: srno});//await the result before next step
         console.log(user.srno)  //you can check 
        if(!user) {
            console.log("invalid user");
            // your logic to tell not student found /wrong username or password, and/or redirect
        }
        const isMatch = await bcrypt.compare(password, user.password) //await the result and this method for comparing the request password and the user's password found
        
            if(!isMatch) {
                //your code to tell Wrong username or password
                res.redirect("/studentlogin");
            } else {
                // your code to access to the login.
                res.redirect("/");
            }
        } catch (err) {
            console.log(err)
        }