I am studying mongoose, and I have a example of a query:
async findOne(condition, constraints) {
try {
let data = await User.findOne(condition, constraints ? constraints : null);
console.log(`findOne success--> ${data}`);
return data;
} catch (error) {
console.log(`findOne error--> ${error}`);
return error;
}
}
In my opinion,this code will catch errors when the method findOne won't work. Then I saw in the console there is a 'findOne success--> null' when the method findOne returns null. How can I make the try/catch work?
I am studying mongoose, and I have a example of a query:
async findOne(condition, constraints) {
try {
let data = await User.findOne(condition, constraints ? constraints : null);
console.log(`findOne success--> ${data}`);
return data;
} catch (error) {
console.log(`findOne error--> ${error}`);
return error;
}
}
In my opinion,this code will catch errors when the method findOne won't work. Then I saw in the console there is a 'findOne success--> null' when the method findOne returns null. How can I make the try/catch work?
Share Improve this question edited Jun 2, 2019 at 20:59 Avi Meltser 4094 silver badges11 bronze badges asked Jun 2, 2019 at 18:01 vinceddvincedd 1411 gold badge1 silver badge4 bronze badges2 Answers
Reset to default 14Mongoose's findOne()
return null
when there is no document found and null
is not an error.
You can use .orFail()
which throw an error if no documents match the given filter. This is handy for integrating with async/await, because orFail()
saves you an extra if statement to check if no document was found:
let data = await User.findOne(condition, constraints ? constraints : null).orFail();
Or just throw an error when there is no result
try {
let data = await User.findOne(condition, constraints ? constraints : null);
if(!data) {
throw new Error('no document found');
}
console.log(`findOne success--> ${data}`);
return data;
} catch (error) {
console.log(`findOne error--> ${error}`);
return error;
}
you can add more conditions in the if of try block and throw a customError which will be catching at the catch block.
i hope this will solve the issue.
please see the below snippet
async findOne(condition, constraints) {
try {
let data = await User.findOne(condition, constraints ? constraints : null);
console.log(`findOne success--> ${data}`);
if(data){
// do your logic
return data;
}
const customError = {
code : 500,
message: 'something went wrong'
}
throw customError
} catch (error) {
console.log(`findOne error--> ${error}`);
return error;
}
}