sac Dahal sac Dahal - 2 months ago 13
Node.js Question

MongoDB : when does an error occur when querying in mongoDb

I had a bug with my

findSomething
function.

function findSomething(req, res, next) {
Myschema.findXXXById(req.params.xid, function (err, doc) {
if (err) res.json({ status: 1, message: messages.NotFound });
res.json({ status: 0, docsInfo: doc });
});
}


The error I got was this


Error: Can't set headers after they are sent.

at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)


I understand that the error is because my if condition is poorly defined so to understand where the error is coming from I want to find a possibility in which the query can encounter a error.

E.g.

if(err) {
// how to get here
}


I tried removing the data from the database so now when it does not get the data it still does not gives an error but return a null instead.

So I wanted to know how can one encounter an error in mongoDb

Answer

You guessed right (in your comment): when an error occurs, you send back an error response but you don't stop the rest of the code from running.

You should make sure that you always call only one operation that will send headers and end the response; operations like that are res.json(), res.send(), res.render(), and some others.

You can restructure your code like this:

if (err) {
  res.json({ status: 1, message: messages.NotFound });
} else {
  res.json({ status: 0, docsInfo: doc });
}

Or even something like this:

if (err) {
  return res.json({ status: 1, message: messages.NotFound });
}
res.json({ status: 0, docsInfo: doc });

(the return statement there is not meant to return a value, but to stop the rest of the code from being run)

Comments