javascript - Insert json file into mongodb using a variable -


I am trying to insert a json file in mjodb. When I enter the JSON entry directly, it works fine. However, when I try to use the data variable from fs.readfile (the same json), the insert fails. I did not get any errors, just data in the collection when I use a variable instead of raw JSON. Here is the code.

  var requires Mongoclant = ('mongodb'). Mongoclant, format = requirement ('use'). Format; MangaCallet.Connect ('Mangode: //127.0.0.1: 27017 / test', function (fault, dB) {if (mistake) becomes a mistake; var fs = require ('fs'); var mydocuments = fs.readFile ('TestNames.json', 'utf8', function (mistake, data) {var archive = db.collection (); archive. Archive (data, function (mistake, docs) {// it gets inserted Collections ("[+ +" + "+"] "); db.close ();})}}; Mongoglent = requires ('mongodb'). Mongoclient, format = requires ( 'Use'). Format; Mongoclit.Connect ('Mongodb: //127.0.0.1: 27017 / test', function (mistake, db) throw {if (mistake); var fs = require ('fs'); var mydocuments = fs.readFile (' TestNames.json ',' utf8 ', function (mistake, data) {var collection = db.collection (' contactcollection '); Collection.insert ({first name: "bill"}, function (mistake, docs) {// The collection gets success by inserting it. NT) {console.log (format ("count =% s", counting)); Console.log ("[" + + "Data +"] "); db.close (); }};});  

You can edit the contents of the file as UTF-8 string Encoding in You JSON.parse () string using needs to be parsed as JSON.

  var fs = require ('fs'); Var mydocuments = fs.readFile ('testNames.json', 'utf8', function (error, data) {var archive = db.collection (); collection.intarch (JSON .pars (data), function, docs ) {// Collections must be successful (work (mistake, count) {console.log (format ("count =% s", counting)); console.log ("[" + "data +"] "); Db.close ();});});  

Comments