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

2023-11-22

我正在尝试使用从查找查询返回的 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),但仍然收到无效的 JSON 错误。有没有办法可以使用 find 查询返回的 mongo 文档并将其转换为 JSON 来发出 POST 请求。

我认为正是这些 ObjectID 使其成为无效的 JSON 文档。


这是实际的答案:

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

所以你可以简单地做mongoResponseObject.toJSON()在响应对象上。

e.g.

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

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

Products.findById(id).lean().then(res => {
    // Here res is JSON
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 MongoDB 文档转换为 JSON 对象 的相关文章

随机推荐