Řekněme tedy, že chci vytvořit dotaz Mongoose do databáze uvnitř cesty expresního příspěvku:
app.post("/login",(req,res)=>{ const username = req.body.username const password = req.body.password User.find({username:username},(err,user)=>{ if (err) handleError(err) //if user exists if (user.length) { //check password if (user.password === password) { //assign jwt, redirect } else { //"username/password is incorrect" } } else { //"username/password is incorrect" } }) })
Zajímá mě funkce handleError. Nejsem si zcela jistý, jaké druhy chyb by se mohly v Mongoose dokonce vyskytnout, protože je to jen jednoduchý dotaz, ale co by mělo být zahrnuto do funkce handleError? A jakou odpověď bych měl v tomto okamžiku odeslat uživateli?
Odpověď
Stačí odeslat chybovou odpověď s popisnou zprávou související s odpovědí Mongoose.
app.post("/login",(req,res)=>{ const username = req.body.username const password = req.body.password User.find({username:username},(error,user)=>{ if (error){ return res.status(400).json({message:"Can not perform find operation.", error: error }); } //if user exists if (user.length) { //check password if (user.password === password) { //assign jwt, redirect } else { //"username/password is incorrect" } } else { //"username/password is incorrect" } }) })