I’m using Model.findById a lot when updating locations and their reviews in MongoDB. The +Getting MEAN+ book covers the 3 scenarios you’ll encounter in your callback:
db.Location.findById(id).select('_id name').exec( (error, location) => {
if (error) {
console.log(`got error: ${error}`);
//return 404
}
else {
if (location) {
console.log(`found it: ${location}`);
//return 200
}
else {
console.log(`not found: ${location}`); //will be null
//return 404
}
}
});
Reading and some experimenting showed that ‘error’ will be set if the id given is invalid, meaning it’s not the expected format for a Mongo Record id. I imagine there can be other causes of an error though, so I’m currently using isValidObjectId function to confirm the id is the correct shape before sending to a query.
This allows for a clear understanding of why a record was not found:
- bad id data was provided
- valid but non-matching id was provided
- some other internal error
Updated example code:
db.Location.findById(id).select('_id name').exec( (error, location) => {
const valid = mongoose.isValidObjectId(id);
if (!valid) {
console.log(`invalid id: ${id}`);
//consider this bad input, record not found.
//return 404
}
if (error) {
console.log(`got error: ${error}`);
//something really bad happened
//return 500
}
else {
if (location) {
console.log(`found it: ${location}`);
//return 200
}
else {
console.log(`not found: ${location}`); //will be null
//valid id format but did not match a location
//return 404
}
}
});