MongoDB删除文档并将其返回

Kar*_*son 7 mongodb

我想找到一个文档,删除它并返回它:

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

我想知道我是否使用了不正确的查询类型.MongoDB有这样的方法吗?

zan*_*ngw 13

可以使用另一个不同的命令.请参阅findAndModify命令.使用选项{query: ..., remove: true, new: false},它将删除单个文档并返回已删除的文档.

此外findOneAndRemove,Mongoose中还有一个API ,查找匹配的文档,将其删除,将找到的文档(如果有)传递给回调.

作者添加:同时删除 .col

        tokens.findAndModify({
            query: {
                token: myTokenVar
            },
            remove: true,
            new: false
        }, function (err, res) {
            if (err)
                throw err;
            console.log(JSON.stringify(res));
        });
Run Code Online (Sandbox Code Playgroud)