使用MongoDB NodeJS驱动程序更新文档

时间:2016-06-25 00:34:36

标签: javascript node.js mongodb

我正在尝试使用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);
});

我失踪了什么?

1 个答案:

答案 0 :(得分:0)

在您的更新声明中,您已写过

"tasks.physician":doc._id

尝试将其更改为:

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

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