skip to Main Content

I am confused on the best practices for using Mongoose with express js with trying to render a page that contains data (with EJS).

I know of the two following methods:

Method 1: using Async/Await

app
  .route("/")
  .get(async (req, res) => {
    const items = await imgModel.find({});
    res.render("home", { items });
  })
  .post((req, res) => {
    res.render("home");
  });

Issue with method 1: no callback function, so I cannot check for error from the call to the DB

Method 2: callback function that allows me to check for errors

app
  .route("/")
  .get((req, res) => {
    imgModel.find({}, (err, items) => {
      if (err) {
        res.status(500).send("error", err);
      } else {
        res.render("home", { items });
      }
    });
  })
  .post((req, res) => {
    res.render("home");
  });

Problem with method 2: No use of Async-Await

I used both methods and they work fine, but I did not have issues with the database so I did not need to handle errors, otherwise I might face issues with method 1 which I think is closer to the preferred practice

2

Answers


  1. async/await errors can be handled with a try/catch…

    app
      .route("/")
      .get(async (req, res) => {
        try {
          const items = await imgModel.find({});
          res.render("home", { items });
        } catch (err) {
          res.status(500).send("error", err);
        }
      })
      .post((req, res) => {
        res.render("home");
      });
    
    Login or Signup to reply.
  2. While @danh response should solve this problem , i would argue using next

       app
          .route("/")
          .get( async (req, res, next) => {
            try {
              const items = await imgModel.find({});
               res.render("home", { items });
            } catch (err) {
               res.status(500)
               next(err)
            }
         })
        .post((req, res) => res.render("home"));
    

    and then the last route you want to add a middleware to handle all errors that might occur

    app.use((err,req,res,next) => {
     if(res.statusCode === 500)
      //do something 
      // for example render a page with a message
     if(res.statusCode === 404)
      // do something
    
    }) 
    

    considering i hate the the default EJS error with passion (when it fails to render a page)
    i would argue that you should do error control during page render

    res.render("home", { items }, (err,html) =>{
      if(err){
       res.status(500)
       return next(err)
      }
      res.status(200).send(html)
    } )
    

    for more on errorHandling check Express docs

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