bobbyz
bobbyz

Reputation: 5046

How to get Express to return the object I just deleted in MongoDB

Feel free to let me know if this isn't a common practice - I'm a fairly new programmer - but I thought I've seen APIs in the past that, when you submit a DELETE request to a resource (/todo/1234), some servers will return the object you just deleted in the response. Is that a thing? If so, I'd be interested in learning how to do it. Here's what I have:

.delete(function (req, res) {
    Todo.findById(req.params.todoId).remove(function (err) {
        if (err) res.status(500).send(err);
        res.send("Todo item successfully deleted");
    });
});

This code does delete the item, but I would like to return the item that got deleted in the response instead of a string message. If that's a normal/okay thing to do. If it isn't normal or okay for some reason, please let me know why and I'll just move on. Or perhaps there's a more common way.

This is what I found in the [RFC 7231 docs][1]:

If a DELETE method is successfully applied, the origin server SHOULD send a 202 (Accepted) status code if the action will likely succeed but has not yet been enacted, a 204 (No Content) status code if the action has been enacted and no further information is to be supplied, or a 200 (OK) status code if the action has been enacted and the response message includes a representation describing the status.

I'm having a hard time interpreting what the 200 response means - is it only kosher to send a string message (Success!) or an object containing a message attribute ({message: "Success!"})? Or can you do whatever you want there? What's the best practice in Express using Mongoose?

Thanks in advance for the help, and sorry for my noobness with HTTP stuff. [1]: https://www.rfc-editor.org/rfc/rfc7231#section-4.3.5

Upvotes: 3

Views: 2420

Answers (1)

Andrey Popov
Andrey Popov

Reputation: 7510

You should use findOneAndRemove! Something like:

Todo.findOneAndremove({ id: req.params.todoId }, function( error, doc, result) {
    // it will be already removed, but doc is what you need:
    if (err) res.status(500).send(err);

    res.send(doc.id);
});

Upvotes: 4

Related Questions