在Mongodb中更新和返回文档 [英] Update And Return Document In Mongodb

查看:317
本文介绍了在Mongodb中更新和返回文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取更新的文档.这是我的原始代码,它成功更新但未返回文档.

I want to get updated documents. This is my original code and it succesfully updates but doesnt return the document.

collection.update({ "code": req.body.code },{$set:  req.body.updatedFields}, function(err, results) {
                        res.send({error: err, affected: results});
                        db.close();
                    });

我曾经使用过toArray函数,但这给出了错误没有提供的回调就不能使用writeConcern":

I used toArray function, but this gave error "Cannot use a writeConcern without a provided callback":

collection.update({ "code": req.body.code },{$set:  req.body.updatedFields}).toArray( function(err, results) {
                    res.send({error: err, affected: results});
                    db.close();
                });

有什么想法吗?

推荐答案

collection.update() 将仅向其自己的回调报告受影响的文档数.

collection.update() will only report the number of documents that were affected to its own callback.

要在修改时检索文档,可以使用 collection.findOneAndUpdate() 代替(以前是 .findAndModify() ).

To retrieve the documents while modifying, you can use collection.findOneAndUpdate() instead (formerly .findAndModify()).

collection.findOneAndUpdate(
    { "code": req.body.code },
    { $set: req.body.updatedFields },
    { returnOriginal: false },
    function (err, documents) {
        res.send({ error: err, affected: documents });
        db.close();
    }
);

更新:在mongoDB中执行.findOneAndUpdate时,请使用{returnNewDocument: true};如果使用猫鼬,则可以使用{new : true}.以上是Node.js驱动程序.

Update: When executing .findOneAndUpdate in mongoDB then use {returnNewDocument: true} or if using mongoose you can use {new : true}. Above is with Node.js driver.

注意:当前从版本2.2 <开始引用Node.js驱动程序. /a>.对于将来的版本,请检查文档中是否有弃用警告,并改用建议的替代方法.

Note: Currently refers to the Node.js Driver as of version 2.2. For future versions, check for deprecation warnings within the documentation and use the recommended alternatives instead.

这篇关于在Mongodb中更新和返回文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆