Reputation: 179
So let's say I want to make a Mongoose query to a database, inside of an Express post route:
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"
}
})
})
My concern is the handleError function. I'm not quite sure what kind of errors could even happen in Mongoose since it's just a simple query, but what should be included in the handleError function? And what response should I send to the user at that point?
Upvotes: 0
Views: 2371
Reputation: 20304
You can just send an error response with descriptive message related to Mongoose response.
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"
}
})
})
Upvotes: 0
Reputation: 1025
You should in my opinion:
async/await
.return res.status(500).json({ message: "Our server are unreachable for now, try again later." });
if this is in production
. If you're in a local
environment, return a JSON payload with the error in it like: return res.status(500).json({ err: <Error> });
.To sumerize, your code should look something like this:
app.post('/login', async (req, res) {
// ES6 Destructuring
const { username, password } = req.body;
// Use findOne instead of find, it speeds up the query
const user = await User.findOne({ username });
if (!user || (user.password !== hashFunction(password))) {
return res.status(403).json({ message: 'Bad credentials' });
}
// assign JWT and redirect
});
Upvotes: 2