user609511
user609511

Reputation: 4261

nodeJS insert data from file

I am trying to insert the data into MongoDB.

when I declare the array locally it works.

var data = [{Name : "Steven", Age: 44},{Name : "John", Age: 54}]

but when I store this file into data.json and read this file. I can not insert.

I got this error :

MongoError: docs parameter must be an array of documents

app.get("/insert", function(request, response) {
  fs.readFile(reqPath , 'utf8', function (err, data) {
    //Handle Error
   if(!err) {
     //Handle Success   
      console.log(data); 
     db.collection("TheData").insertMany(data, function(err, r) { console.error(err);});
     //console.log("after" +defaultUsers); 
    }else {
       //Handle Error
       console.error(err);
    }
  }) 
});

even though, the output of data is the same as if I declare it above.

Upvotes: 0

Views: 162

Answers (1)

mohammad javad ahmadi
mohammad javad ahmadi

Reputation: 2081

type of data in this callback fs.readFile(reqPath , 'utf8', function (err, data) is String. you should convert your out put to json.

Of course you need to change the way the array is written to the file as well. And use double quotes for the keys

data.json:

[{"Name" : "Steven", "Age": 44},{"Name" : "John","Age": 54}]

update your code

app.get("/insert", function (request, response) {
  fs.readFile(reqPath, 'utf8', function (err, data) {
    //Handle Error
    if (!err) {
      //Handle Success   
      console.log(data);
      data = JSON.parse(data);
      db.collection("TheData").insertMany(data, function (err, r) { console.error(err); });
      //console.log("after" +defaultUsers); 
    } else {
      //Handle Error
      console.error(err);
    }
  })
});

Upvotes: 3

Related Questions