I am trying to output specific messages on specific responses.
Here is my code:
.post(function(req, res) {
var user = new User(req.body);
user.save(function(err) {
if(err) {
if(err.code == 11000)
res.status(409).json(customHTTPcodeReponses.exists(req.body.email));
};
User.findById(user._id, function(err, createdUser) {
res.status(201).json(customHTTPcodeReponses.created(createdUser));
});
});
});
Flow:
- Posting data. I get 201.
- Posting same data again. I get 409.
- Posting same data again. I get "Could not get any response (POSTMAN)"
Console error: _http_outgoing.js:335 throw new Error('Can\'t set headers after they are sent.'); [nodemon] app crashed - waiting for file changes before starting...
What could cause this?
User.findByIdcode within anelsestatement? (if(err){ .... } else { User.findById........ })rescan be called twice. I avoided this by typing in return as result ofif(err). But I could use else statement as well.