无法使用 document.findOne() 获取文档。

huangapple go评论59阅读模式
英文:

Unable to get document using document.findOne()

问题

我尝试使用document.findOne()来获取文档,但它的值显示为未定义。以下是我的代码:

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");
		}
	});
	
})

我正在使用express-session实施会话身份验证。在这里,当我记录用户时,它显示模式和许多我不知道的其他内容(错误信息太长)。user.srno 也显示为未定义。我该如何修复它?

我尝试使用回调函数,它确实为我提供了正确的文档。但我希望查询能够返回正确的文档并将其存储在user中。使用回调函数的方式如下:

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");
		}
	});
	
})
英文:

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");
	}
});

})`

答案1

得分: 1

你面临的错误是因为你的代码中没有使用async await。在你的函数定义中使用async,然后在搜索数据库的地方使用await。

你的代码应该像这样:

app.post("/studentlogin", async (req, res) => {
// 你的代码
const user = await Student.findOne({ srno: req.body.srno });
// 你的代码
}

使用console.log(user)来进行验证。

希望能有所帮助。

英文:

The error you are facing is because you are not using async await in your code. use async in your function definition then use await where you are searching the database.

const someFunction = async(req,res)=>{
// your code
 const user=await Student.findOne({srno:req.body.srno});
// your code
}

Your code should look like this.

app.post("/studentlogin", async(req,res)=> {
// your code
const user=await Student.findOne({srno:req.body.srno});
// your code 
}

console.log(user) to verify.
Hope it helps.

答案2

得分: 1

你需要在从数据库查询中等待结果之后再执行下一个任务,例如比较密码。看起来你只是尝试登录,而不是注册新用户,所以最好使用Bcrypt的比较方法,像这样:

app.post("/studentlogin", async (req, res) => {
    const { srno, password } = req.body; // 解构你的请求以提高可读性
    try {
        const user = await Student.findOne({ srno: srno }); // 在进行下一步之前等待结果
        console.log(user.srno); // 你可以检查

        if (!user) {
            console.log("无效用户");
            // 告诉用户未找到学生/用户名或密码错误的逻辑,和/或重定向
        }

        const isMatch = await bcrypt.compare(password, user.password); // 等待结果并使用此方法比较请求的密码和找到的用户密码

        if (!isMatch) {
            // 告诉用户用户名或密码错误的代码
            res.redirect("/studentlogin");
        } else {
            // 访问登录的代码
            res.redirect("/");
        }
    } catch (err) {
        console.log(err);
    }
});
英文:

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)
    }

huangapple
  • 本文由 发表于 2023年1月8日 00:35:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75041991.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定