Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a MongoDB document to JSON Object

I am trying to make a post request with the MongoDB document returned from find query, as the request body in NodeJS.But on the server I'm getting the Error : Invalid JSON. Below is the document that I'm trying to POST

{
    "_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
}

and here is the code that I wrote to make the POST request

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

I also tried using JSON.stringify(doc), but still got the Invalid JSON error. Is there a way I can use mongo document returned by the find query and convert it to JSON to make the POST request.

I think those ObjectID is what making it an invalid JSON document.

like image 598
Mahtab Alam Avatar asked Jul 01 '16 11:07

Mahtab Alam


1 Answers

Here's the actual answer:

If you want to convert a mongo object to JSON object. There's a utility method in every mongo object toJSON

So you can simply do mongoResponseObject.toJSON() on the response object.

e.g.

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

Alternatively you can directly get the JSON object by using the .lean() like this.

Products.findById(id).lean().then(res => {
    // Here res is JSON
})
like image 178
Sharrc Avatar answered Nov 15 '22 04:11

Sharrc