I am new to express and JS in general. I am trying to get an object from mongodb database. I can get the object when it exists, however when it doesn’t I want to send a text/custom page or do anything in fact, but the app keeps crashing.
I tried several codes and they all did not redirect me to but just crashed and sent me to a random page saying " 404 This page could not be found. Page Developed by @yandeu"
I tried messing around with the code in every way possible
app.get("/item/:id",(req,res)=>{
Item.findById(req.params.id).then((item)=>{
if(item){
res.json(item)
}else{
res.sendStatus(404)
// and also these lines
//item = {"Status":"not Found"}
// res.json(item)
//and also this line
//res.send("404 page")
//res.sendFile(__dirname+"/404.html")
}
}).catch(err =>{
if(err){
throw err
}
})
})
after that i deleted everything and kept the findById function and I think (not sure) that it throws thats why the app crashes to i put the whole thing in a try and catch and the same problem happens
app.get("/item/:id",(req,res)=>{
try{
Item.findById(req.params.id).then((item)=>{
res.json(item)
})
}
catch(err){
if(err){
throw err
}
console.log("not found")
}
})
I have no idea what is happening, and I am lost and can’t find anything online.
any help is appreciated
thanks in advanced
2
Answers
my intution was correct findById() throws an error and crashes the app when the object does not exist, I just wasn't familar with handelling errors in JS. Anyways here is the correct code if anyone needs it in the future
The mongoose
Model.findById()
method is an asynchronous task. That means you need to wait for it to be settled before you can use it’s return value.I appreciate that to a beginner in JavaScript, handling asynchronous code can be confusing. It is typically done in two ways. Either with Callbacks or using Promises.
Mongoose used to support callbacks but has now moved to promises. That means you need to use either
then().catch()
blocks or the preferredasync/await
pattern withtry/catch
blocks.In your answer you have correctly identified a solution using
then().catch()
blocks but having nestedthen()
blocks can lead to readability and maintainability problems similar to those encountered when using callbacks.Here is an example using
async/await
:You will find that all of the database queries in mongoose are asynchronous so you will need to remember this.
Good luck with your learning.