C O C O - 3 months ago 10
Node.js Question

Retrieving the latest entry and then deleting it right away with MongoDB and Mongoose?

Forgive me for my ignorance but I'm more of a C# developer. This is my first NodeJS program. I'm trying to write a program where my program calls a GET to my node.js server. When the server receives that request I want it to send the latest entry from MongoDB and delete it immediately so it cannot be reused. I want this to be done server-side.

Here's what I have below,

router.get('/', function(req, res, next) {
Todo.findOne({}, {}, { sort: { '_id' : -1 } }, function(err, post) {
res.json(post);
Todo.remove({_id: -1});
});
});

Answer

Consider using the findOneAndRemove() API which is an atomic update that issues a mongodb findAndModify remove command, hence always returns the deleted document. Use the sort option to choose which document to delete since multiple docs will be returned by the query:

router.get('/', function(req, res, next) {
    var query = {},
        options = { "sort": { "_id": -1 } }; // or { "sort": "-_id" } 
    Todo.findOneAndRemove(query, options, function(err, post) {
        if (err) console.error(err);
        res.json(post);
    });
});