skip to Main Content

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


  1. Chosen as BEST ANSWER

    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

    app.get("/item/:id",(req,res)=>{
       Item.findById(req.params.id).then((item)=>{
            res.json(item)
        }).catch(err =>{
            if(err){
                res.sendFile(__dirname+"/404.html")
                //or whatever response you want to send
            }
        })
    })
    

  2. 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 am new to express and JS in general

    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 preferred async/await pattern with try/catch blocks.

    In your answer you have correctly identified a solution using then().catch() blocks but having nested then() blocks can lead to readability and maintainability problems similar to those encountered when using callbacks.

    Here is an example using async/await:

    app.get("/item/:id", async (req, res) => { //< Marks the callback as async
       try{
          const item = await Item.findById(req.params.id); //< Use of await keyword
          if(!item){ //< item will be null if no matches in database
             return res.status(400).json({ //< Early return if no match
                message: 'No Item found'
             })
          }     
          return res.status(200).json({
             item: item
          });
       } catch(err){
          console.log(err); //< Log the actual error so you can check
          return res.status(500).json({
             message: 'Error on server'
          });
          //or whatever response you want to send
       }
    });
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search