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
async/await errors can be handled with a try/catch…
While @danh response should solve this problem , i would argue using next
and then the last route you want to add a middleware to handle all errors that might occur
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
for more on errorHandling check Express docs