【问题标题】:Updating Documents using MongoDB NodeJS Driver使用 MongoDB NodeJS 驱动程序更新文档
【发布时间】:2016-06-25 00:34:35
【问题描述】:

我正在尝试使用 mongodb nodejs 驱动程序更新文档,我没有使用 mongoose 只是普通的 mongodb nodejs 驱动程序。但是由于更新的文档,我变得不确定。无法找出问题所在。

var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var assert = require('assert');
var url = 'mongodb://localhost:27017/cmecore';
var url2= 'mongodb://localhost:27017/cmeprovisioning';


var findAndUpdateDocuments = function(db) {

  MongoClient.connect(url2, function(err, db2) {

    console.log("Connected to cmeprovisioning");
    var updated=0;

    var cursor =db.collection('physicianTasks').find({"study":"cod","phase":"mansa2","taskStatus":"Complete"});
    cursor.each(function(err, doc) {

       var physicianTaskDocument=doc;
       if (doc != null) {
           console.log(JSON.stringify(doc.result));

            var assign=doc.assignedTo.toString();
            var phasePhysician=null;

            db2.collection('phasePhysician').findOne
            ({"study":"cod","phase":"mansa2","physicianId":assign},function(err,doc){
              phasePhysician=doc;
              console.log("ID "+phasePhysician._id);
              db2.collection('rhimeReport').updateOne(
                    {"study":"cod","phase":"mansa2","recordStudy":"codstudy",
                    "recordPhase":"mansa2","rhimeTaskId":physicianTaskDocument.rhimeTask.toString(),
                    "recordId":physicianTaskDocument.record.toString(),
                    "tasks.physician":new ObjectID(phasePhysician._id.toString())
                    },
                   {
                     $set: { "tasks.result": physicianTaskDocument.result }
                   },
                   function(err, r) {
                      updated=updated+1;
                      console.log("After Update "+updated +" "+r );
                    }
                  );
            });
       }
  });


  });

}

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected to cmecore");
  findAndUpdateDocuments(db);
});

我错过了什么?

【问题讨论】:

  • 真实数据如何?更新?由于异步性质,findDocuments 中的最后两个 console.log 不会按预期工作
  • 真实数据没有更新,你能告诉我我应该做些什么改变
  • 它的意思是,您对 updateOne 的查询与任何文档都不匹配。 mongoose 会在字符串、数字、布尔值之间进行自动数据转换,但原生驱动不会对它做任何事情。
  • 你能分享你的数据库结构吗?

标签: javascript node.js mongodb


【解决方案1】:

在你写的更新声明中

"tasks.physician":doc._id

尝试将其更改为:

"tasks.physician": mongodb.ObjectID.createFromHexString(doc._id);

"tasks.physician": mongodb.ObjectID(doc._id) 

【讨论】:

  • 我更改并使用了 ObjectID,它确实匹配文档,但更新不起作用。我很确定它与异步调用有关
  • 我已经更新了代码并删除了不必要的异步调用。但是在更新的文档中,我仍然没有定义。更新中的匹配标准是正确的,我通过在更新前使用查找进行了测试。任何线索有什么问题。
  • 什么是记录 ID 和任务 ID?他们是对象 id 吗?如果是,那么也改变它们
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-08
  • 2021-11-02
  • 1970-01-01
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
相关资源
最近更新 更多