Reputation: 51
in my node app mongoDB throwing an error for a route only some times.
this is my route:
app.get("/categories/:catName", async function(req, res) {
const name = req.params.catName;
console.log(name);
var catItem;
await Category.findOne({ name: name }, function(err, foundItem) {
if (err) {
console.log(err);
} else {
catItem = foundItem;
}
});
await Product.find({ category: catItem._id }, function(err, foundItems) {
if (err) { console.log(err) } else {
res.render("category.ejs", { category: catItem, products: foundItems });
}
});
});
when I start my server and get data from this rouut for the first time everything is working fine. but when I going back and coming to the same route again I am getting an error as follows;
(node:24464) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_id' of undefined
at D:\DEV\WEB\craftyscale\app.js:58:44
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:24464) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:24464) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
what is going wrong here? can someone help me.
Upvotes: 0
Views: 501
Reputation: 989
I think your syntax is not correct. In this portion of the code:
await Category.findOne({ name: name }, function(err, foundItem) {
if (err) {
console.log(err);
} else {
catItem = foundItem;
}
});
You are both treating as a promise, but at the same time providing a callback to the function. If you're using the callback version, you must put your Product.find logic inside of the callback; otherwise use await in the following way (same issue with your call to Product.find, mixing async/await and callback):
const catItem = await Category.findOne({ name: name });
const foundItems = await Product.find({ category: catItem._id });
if (err) { console.log(err) } else {
res.render("category.ejs", { category: catItem, products: foundItems });
}
You can find more information here: https://mongoosejs.com/docs/api.html#model_Model.findOne . You will see that async/await and callback ways are used separately.
Upvotes: 2