user3807691
user3807691

Reputation: 1304

read data from json file and insert into mongodb (meteorjs)

I have a file that contains data in json format.

{
"channelName" : "practice",
"startDate" : ISODate("2017-07-22T06:29:35.681Z"),
"endDate" : ISODate("2017-08-22T06:29:35.681Z")
}

Above is the file format. Filename is test.json. I want to read it at my server side and insert into db. I tried using Assets.getText but failed reading the file in json format. Following is the code i wrote

Assets.getText('channelTestData.json', function(err, res){
// var test = JSON.parse(res);
// console.log('tets : ' + test);
Channel.insert(res);
// Channel.save(res);
});

If i use JSON.parse or EJSON.parse, it throws an error.

Upvotes: 2

Views: 258

Answers (1)

mparkitny
mparkitny

Reputation: 1195

You dates are invalid JSON. You probably get this error:

Exception in callback of getAsset SyntaxError: Unexpected token I

You can find valid JSON data types here(wikipedia). Your JSON file should looks like:

{
  "channelName" : "practice",
  "startDate" : "2017-07-21T11:59:26.040Z",
  "endDate" : "2017-07-21T11:59:26.040Z"
}

If you are creating new Data object you can use below code to get valid JSON which won't throw errors.

new Date().toJSON()

Also is it worth to mention that files you would like to get using #getText() should be in the private directory in your app folder. More about this topic can be found in the Meteor docs

Upvotes: 1

Related Questions