1

I want to insert data for whole current month i.e. November every day of this month and every hour of each day and every minute of each hour and every second of each minute. I tried the following code which I tried for one day.

const data = [
    {
      'name': 'Name 10'
    }, {
      'name': 'Name 9'
    }, {
      'name': 'Name 8'
    }, {
      'name': 'Name 7'
    }, {
      'name': 'Name 6'
    }, {
      'name': 'Name 5'
    }, {
      'name': 'Name 4'
    },
    {
      'name': 'Name 3'
    },
    {
      'name': 'Name 2'
    },
    {
      'name': 'Name 1'
    }
];

const HOURS = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24];
const MINUTES = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59];
    for (let i = 0; i < data.length; i++) {
        for (let h = 0; h < HOURS.length; h++) {
            const hour = new Date().setHours(HOURS[h]);
            for (let m = 0; m < MINUTES.length; m++) {
                const n = data[i].name;
                const value =  Math.floor(Math.random() * (10 - 0 + 1)) + 0;
                const timestamp = new Date(hour).setMinutes(MINUTES[m]);
                new MongoCollection({ 'name': n, 'value': value, 'timestamp': timestamp }).save();
            }
        }       
    }

Any help would be appreciated.

Om3ga
  • 30,465
  • 43
  • 141
  • 221

1 Answers1

0

Why do you create arrays and use HOURS.length and MINUTES.length? for (let h = 0; h < 24; h++) and for (let m = 0; m < 60; m++) does the same.

What is the purpose of - 0 and + 0?

Inserting the documents one-by-one will let to serious performance issues.

Anyway, I would suggest moment.js library, would be similar to this.

for (let d of data) {
   var startTime = moment().startOf('month');
   var endTime = moment().endOf('month');
   var docs = [];
   while (startTime.isBeforeOrSame(endTime)) {
      docs.push({ 
          name: d.name, 
          value: Math.floor(Math.random() * 11), 
          timestamp: startTime.toDate() 
      });
      startTime.add(1, 'second');
   }
   db.collection.insertMany(docs);
}

Or maybe put array docs even at top level.

Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110
  • How can I try that with mongoose? I tried `new MongoCollection().insertMany(docs)`, `MongoCollection.insertMany(docs)`, `MongoCollection().insertMany(docs).save()`, `new MongoCollection().insertMany(docs).save()` none of them worked. – Om3ga Nov 28 '21 at 07:44
  • Sorry, I never worked with mongoose. See https://stackoverflow.com/questions/10266512/how-can-i-save-multiple-documents-concurrently-in-mongoose-node-js#:~:text=Mongoose%204.4%20added%20a%20method%20called%20insertMany – Wernfried Domscheit Nov 28 '21 at 07:55