Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import Json file into Mongoose

I need to import a JSON file to a data base Mongoose. This should be a script that should be run daily.

I have my JSON as follows :

[
 {
   "grant_title": "name SRL",
   "id": "30579843531",
   "total_amount": "551954"
},{
   "grant_title": "AADI CAPIF ASOCIACION CIVIL",
   "id": "30574449967",
   "total_amount": "37050"
},{
   "grant_title": "LA CAMPAÑOLA S.A",
   "id": "23311183419",
   "total_amount": "139292"
  }
]

I need this information to be stored in a database .

This should be whether or if a script NodeJS (express). Please be clear , because I am a beginner .

like image 731
Manuel Paiva Avatar asked Sep 13 '25 11:09

Manuel Paiva


1 Answers

Let's take this gradually. First off you are going to need to either create a CRON job, or use a NodeJS scheduler such as agenda to execute your function at a time interval.

Now... inside your function you need to load your JSON file into NodeJS.

var json = require('/path/to/file.json');

Finally... use insertMany to do a bulk insert into your collection.

db.collectionName.insertMany(json, function(err,result) {
   if (err) {
     // handle error
   } else {
     // handle success
   }
});

EDIT: Here is an example of using Agenda in NodeJS to run a program daily at 11:30 AM

var Agenda = require('agenda');

startScheduler = function() {
    // Set the scheduler utilizing Agenda
    var agenda = new Agenda({db: {address: 'url/to/database'}});

    agenda.define('RUN AT 1130 AM', function(job, done) {
        // your function goes here...
        done();
    });

    agenda.on('ready', function() {
        // CRON SYNTAX
        // * * * * * *
        // Minute / Hour / Day / Month / Day of week (0-6) Sunday-Saturday
        agenda.every('30 11 * * *', 'RUN AT 1130 AM'); // Run daily at 11:30 AM

        agenda.start();
    });
};

startScheduler();
like image 151
dyouberg Avatar answered Sep 16 '25 02:09

dyouberg