【问题标题】:How to convert a MongoDB document to JSON Object如何将 MongoDB 文档转换为 JSON 对象
【发布时间】:2016-11-03 19:06:51
【问题描述】:

我正在尝试使用从查找查询返回的 MongoDB 文档作为 NodeJS 中的请求正文发出发布请求。但是在服务器上我收到错误:无效的 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
}

这是我为发出 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)
                      }
                   });
});

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

我认为那些 ObjectID 是导致它成为无效 JSON 文档的原因。

【问题讨论】:

标签: json node.js mongodb


【解决方案1】:

以下是实际答案:

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

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

例如

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

您也可以像这样使用.lean() 直接获取JSON 对象。

Products.findById(id).lean().then(res => {
    // Here res is JSON
})

【讨论】:

  • toJSON 是一个 mongoose 实用函数,因此它仅在将 mongoose ORM 与 mongoDB 一起使用时可用
【解决方案2】:

您需要将对象 id 转换为字符串 ie。

var result = {
  "_id": ObjectId("5739a6bf3f1b41477570dc89"),
  "taskCount": 2,
  "study": "cod"
};
//now convert to string 
result=result._id.toString();
//now you can use the result

【讨论】:

    【解决方案3】:

    试试这个,

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

    希望对您有所帮助。

    【讨论】:

      【解决方案4】:

      在 robomongo 中试试这个

      var cursor = db.getCollection('X').find({},{})
      
      while(cursor.hasNext()) {
          print(JSON.stringify(cursor.next()))
      }
      

      【讨论】:

        猜你喜欢
        • 2011-09-22
        • 2016-12-22
        • 1970-01-01
        • 2018-06-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-09
        • 2015-10-06
        • 1970-01-01
        相关资源
        最近更新 更多