Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB remove document and return it [duplicate]

Tags:

mongodb

I would like to locate a document, remove it and also return it:

        tokens.col.remove({
            token: myTokenVar
        }, function (err, res) {
            if (err)
                throw err;
            console.log(JSON.stringify(res)); // <-- this results in null
        });

I'm wondering if I'm using the incorrect query type for this. Does MongoDB have such a method?

like image 565
basickarl Avatar asked Feb 01 '16 13:02

basickarl


1 Answers

It is possible with another different command. Refer to findAndModify command. With the options to {query: ..., remove: true, new: false}, it will delete a single document and return the removed document.

Also there is one API findOneAndRemove in Mongoose, Finds a matching document, removes it, passing the found document (if any) to the callback.

Added by author: Also remove .col

        tokens.findAndModify({
            query: {
                token: myTokenVar
            },
            remove: true,
            new: false
        }, function (err, res) {
            if (err)
                throw err;
            console.log(JSON.stringify(res));
        });
like image 77
zangw Avatar answered Oct 24 '22 20:10

zangw