gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:49:39 26 4
gpt4 key购买 nike

我正在尝试使用从查找查询返回的 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() 即可。

例如

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
})

关于json - 如何将 MongoDB 文档转换为 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38144236/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com