Thursday, 16 March 2017

Output JSON file and save to mongoDB using node

I have the current scheme below in JSON. I am currently writing and saving the JSON file in my local directory with node and all is working fine.

Each time a user refreshes the browser, the current JSON is being overwritten with a new data set.

I would like to save a record of the data in MongoDB each time a user refreshes, oppose to it constantly being overwritten each time, which is the case now.

I have very little experience in MongoDB, so if anyone has ran into a similar scenario it would be great to see how you went about accomplishing this.

JSON:

[
    {
        "key": "1",
        "date": "03/03/17",
        "time": "6:54am",
        "price": "520.70"
    },
    {
        "key": "2",
        "date": "03/04/17",
        "time": "8:59pm",
        "price": "1220.70"
    },
    {
        "key": "3",
        "date": "03/05/17",
        "time": "9:15am",
        "price": "550.22"
    },
    {
        "key": "4",
        "date": "03/05/17",
        "time": "10:04pm",
        "price": "120.70"
    }
]

Server.js:

....

fs.writeFile(__dirname + '/data/output.json', JSON.stringify(result, null, 4), function(err){
      if(err) {
        throw err;
      } else {
        console.log('File successfully written!');
      }
    });



via user992731

No comments:

Post a Comment