Home > Software engineering >  Mongoose not returning HTTP status code 204 on delete
Mongoose not returning HTTP status code 204 on delete

Time:10-25

I am using mongoose for mongodb and trying to delete a record. A standard REST API should return in a 204 response on delete. However mongoose is returning 200

  return await ppc.deleteOne({ _id: id });

With response having deletedCount

data:
    deletedCount: 1
status: 200

or using

  return await ppc.findOneAndRemove({ _id: id});

returns same 200 with body. Is there any delete API which returns 204 by default?

Like in spring boot or spring data rest it returns 204 by default for a successful delete request. I understand if I need body in response I would need to send 200 for a proper REST API convention. However if I need to return the 204 myself with mongoose, mongo db I would need to check for deletedCount first ,which I can do either on backend or frontend which is a little extra work. I wanted to ensure is there some setting or some other API which defaults it to 204?

Issue with 200 status code is that mongoose even return 200 for a ID which doesn't exists.

CodePudding user response:

You should separate the function of Mongodb as a database vs the HTTP response code your app returns, there is no relation between the two.

200 is the default "success" response code as it's returned because your app successfully executes the code with no errors. mongoose or mongodb are not the ones returning the status.

What it sounds like you want to be doing is incorporate some basic logic into your routes, like so:

const delResult = await ppc.deleteOne({ _id: id });
response.json({statusCode: 402, ...delResult})

With mongoose you can also prebuild triggers to execute after certain operations to handle this type of custom logic for you, that's how you avoid code duplication throughout your app.

  • Related