mongoose findOne
query throws Interal Server Error (500)
when looking for a value that doesn't exists.
I'm pretty sure it should return null
or empty array instead of throwing error.
Mongoose version: ^5.8.7
First attempt
router.get('/:myId', async(req, res, next) => {
const myId = req.params.myId;
await myDocument.findOne({ _id: myId }, (err, myData) => {
if (!myData) {
res.status(404).render('404');
} else {
res.render('myPage', myData);
}
}).exec()
});
second attempt
router.get('/:myId', async(req, res, next) => {
const myId = req.params.myId;
const myData = myDocument.findOne({_id: myId}).exec();
if (myData) {
//render normal page
}
// render 404 page
});
According to documentation, this should NOT happen.
Note: conditions is optional, and if conditions is null or undefined, mongoose will send an empty findOne command to MongoDB, which will return an arbitrary document. If you're querying by _id, use findById() instead.
Also tried to use findById()
and find()
. All cases the same happens.
It works perfectly when I pass a valid ID parameter.
How to search for data without throwing http error in case Id doesn't exists in collection?
CodePudding user response:
router.get('/:myId', async(req, res, next) => {
You should check your route
CodePudding user response:
You should try this code. First assign the ObjectId on top where are dependencies being called. MongoDB id is not string. It is adviseble to pass the ObjectId.
const { ObjectId } = require('mongodb');
router.get('/:myId', async(req, res, next) => {
const myId = ObjectId(req.params.myId);
const myData = await myDocument.findOne({_id: myId}).exec();
if (myData) {
//render normal page
}
// render 404 page
});
CodePudding user response:
The error was actually happening during the page render.
In fact, mongoose
does NOT throws any error in this case.
I was trying to render a html
page while setting ejs
as View Engine
.
Apparentely we can't mix things.