2

I am learning Backend development using node.js and mongodb. Mongoose has a method Model.save(function(err,model)) what status code must be returned when for some reason the document could not be saved.

In terms of code:

Model.save(function(err,model){
if(err)
    res.status(5xx).send(err);
if(!model) {
    //executed when unable to save document IMHO correct me I am wrong
    res.status(xxx).send("Unable to save the model in database");
}
});
logdev
  • 292
  • 6
  • 22
  • 1
    If it's an error due to bad request then you should send status 400. If it's because of some internal server problem then it needs to be status 500. – Nishant Jain Jul 01 '19 at 17:36
  • How do I know the reason why the document could not saved? – logdev Jul 01 '19 at 17:38
  • I assume that if that callback has a truthy `err` value, then something went wrong and `err` **is** the reason; and if not then `model` will be truthy. Why are you wondering about the reasonless (and potentially never-occurring) condition that there is no `err`, and also no `model`? Does the documentation for `Model.save` say that can ever occur? I'm inclined to assert that the Model.save API is malfunctioning in that case; and therefore you can _also_ return 500 -- potentially with the reason that Model.save has a bug. – Wyck Jul 01 '19 at 19:42
  • Does this answer your question? [What HTTP status code should I return for POST when no resource is created?](https://stackoverflow.com/questions/55685576/what-http-status-code-should-i-return-for-post-when-no-resource-is-created) – Michael Freidgeim Jul 07 '22 at 11:47

2 Answers2

1

Well, this is a tricky question but I have to tell you 422 is not a valid state.

What I imagine is you are trying to say there was an error, it might be a network problem, service not ready (Mongo down, unresponsive) or similar. There is no 4xx code to represent that, if you want to use any 4xx it might not be representing the truth.

The usual response is 503 because it's unavailable which is what I imagine you want to communicate.

Maximiliano Rios
  • 2,196
  • 2
  • 20
  • 34
  • I am talking about the if(!model) condition which is executed when the document could not be saved for some reason. – logdev Jul 01 '19 at 17:43
  • I have edited the code in question from if(err) res.status(422) to if(err) res.status(5xx) but that is not what I wanted to ask. – logdev Jul 01 '19 at 17:44
1

You could use any code which is represented by 4xx or 5xx. Using 2xx or 3xx for reporting errors prevents error detection by http-aware softwares. Moreover you can send a specific error message by using

JSON.stringify(error, undefined, 2);

checkout this link where I explained what this method does https://stackoverflow.com/a/56773148/8284444

Harsh Mandalgi
  • 204
  • 2
  • 5