I have the following express code. If I try to get a document with a non-existent id, I get nothing. The problem is that I get 200 as response status and I don't get the Failed message. The code jumps every time into "then".
const Mymodel = require('../model/Mymodel');
const Single = (req, res) => {
const id = req.params.id;
Mymodel.findById(id)
.then(result => {
res.send(result);
})
.catch(err => {
console.log(err);
res.status(404).send({"Failed": "Document not found"});
});
}
CodePudding user response:
your finding query response is null so this is not an error. if you send res.status(404).send({"Failed": "Document not found"}); response for not found use this.
const Mymodel = require('../model/Mymodel');
const Single = (req, res) => {
const id = req.params.id;
Mymodel.findById(id)
.then(result => {
if(result){
res.send(result);
}else{
res.status(404).send({"Failed": "Document not found"});
}
})
.catch(err => {
console.log(err);
res.status(404).send({"Failed": "Document not found"});
});
}