I am confused on the best practices for usi开发者_C百科ng 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 erro
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 preffered practice
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");
});
精彩评论