如何将 MongoDB 文档转换为 JSON 对象

Mah*_*lam 7 json mongodb node.js

我正在尝试使用从 find 查询返回的 MongoDB 文档作为 NodeJS 中的请求正文发出 post 请求。但是在服务器上我收到错误:无效的 JSON。以下是我尝试发布的文档

{
    "_id" : ObjectId("5739a6bf3f1b41477570dc89"),
    "taskCount" : 2,
    "study" : "cod",
    "phase" : "mansa2",
    "rhimeTaskId" : "5739a6bec4567f6e737fd3db",
    "recordId" : "5726f3cfc4567f6e737fc3ab",
    "recordStudy" : "codstudy",
    "recordPhase" : "mansa2",
    "recordLanguage" : "Punjabi",
    "recordScript" : "Latin",
    "_state" : "CodingComplete",
    "tasks" : [
        {
            "physician" : ObjectId("5739a6bd3f1b41477570dc78"),
            "stage" : "Coding",
            "result" : {
                "cod" : "C15",
                "feedback" : {
                    "narrativeLength" : "Adequate",
                    "positiveSymptomsIncluded" : "Only Positive",
                    "certainty" : "High"
                },
                "keywords" : [
                    "52 yr male, died of food pipe cancer, suffered pain upper abdomen, investigated,FNAC confirmed Cancer, Put on Chemotherapy, multiple cycles, died at home, had fever with chills occasionally"
                ]
            }
        },
        {
            "physician" : ObjectId("5739a6bd3f1b41477570dc79"),
            "stage" : "Coding",
            "result" : {
                "cod" : "C15",
                "feedback" : {
                    "narrativeLength" : "Inadequate",
                    "positiveSymptomsIncluded" : "Only Positive",
                    "certainty" : "High"
                },
                "keywords" : [
                    "severe pain abdomen, ultrasonography revealed food pipe cancer, chemotherapy given, died"
                ]
            }
        }
    ],
    "__v" : 2
}
Run Code Online (Sandbox Code Playgroud)

这是我编写的用于发出 POST 请求的代码

var MongoClient = require('mongodb').MongoClient;
var request = require('request');
var assert = require('assert');
var cmeprovisioning= 'mongodb://localhost:27017/cmeprovisioning';

MongoClient.connect(cmeprovisioning, function(err, db) {
  assert.equal(null, err);
  var count=0;
  console.log("Connected to cmeprovisioning");

         var cursor =db.collection('rhimeReport').find(
                    {"study":"cod","phase":"mansa2","recordStudy":"codstudy",
                     "recordPhase":"mansa2","_state":"CodingComplete"
                    });


                 cursor.each(function(err, doc) {
                      assert.equal(err, null);
                      if (doc != null) {
                         console.dir(doc);
                         count=count+1;
                         request({url: "http://cme.host.net:8081/cme-provisioning/update",
                                  method: "POST",json: true,
                                  headers: {"content-type": "application/json"},
                                  json: doc
                                 },function(e,r,b){

                                       console.log("POST Error "+count+" "+e)
                                       console.log("POST Response "+count+" "+r)
                                       console.log("POST BODY "+count+" "+b)
                                 });


                      } else {
                         console.log("Some Error : "+err)
                      }
                   });
});
Run Code Online (Sandbox Code Playgroud)

我也尝试使用 JSON.stringify(doc),但仍然收到无效 JSON 错误。有没有办法可以使用 find 查询返回的 mongo 文档并将其转换为 JSON 以发出 POST 请求。

我认为这些 ObjectID 使它成为无效的 JSON 文档。

小智 8

这是实际的答案:

如果要将 mongo 对象转换为 JSON 对象。每个 mongo 对象都有一个实用方法toJSON

所以你可以简单地mongoResponseObject.toJSON()对响应对象执行操作。

例如

Products.findById(id).then(res => {
    const jsonRes = res.toJSON();
    // Here jsonRes is JSON
})
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用.lean()类似这样的方法直接获取 JSON 对象。

Products.findById(id).lean().then(res => {
    // Here res is JSON
})
Run Code Online (Sandbox Code Playgroud)


Lal*_*ami 1

尝试这个,

var cursor =db.collection('rhimeReport').find(
       {"study":"cod","phase":"mansa2","recordStudy":"codstudy",
        "recordPhase":"mansa2","_state":"CodingComplete"});

cursor.toString();
......
Run Code Online (Sandbox Code Playgroud)

希望这有帮助。