S
S
Sahnen2018-02-15 19:07:10
MongoDB
Sahnen, 2018-02-15 19:07:10

How to initialize Mongodb with data?

I set the initial data for a DB a trace. way:

const ModTpl = require('../models/mod_tpl');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/testdb', { useMongoClient: true });

//Здесь набор самих данных
const data = [ ... ];

let done = 0;

for (let i = 0; i < data.length; i++) {
  data[i].save(function(err, result) {
//    if (err) {
//      console.log(i, err);
//      mongoose.disconnect();
//      return;
//    }

    done++;
    if (done === data.length) {
      exit();
    }
  });
}

function exit() {
  mongoose.disconnect();
}

There are about 50,000 elements in the array, the data is homogeneous. Initialization is started from the terminal with the node initdata.js command.
As a result, a different number of elements is added to the database all the time - from 18000 to 25000. No errors are displayed.
How to ensure that all elements are added to the database?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Tsvetkov, 2018-02-15
@Sahnen

I would use async lib something like this:

const async = reuire('async');

let queue = async.queue(function(task, callback) {
    task.save(callback);
}, 10);

queue.drain = function() {
    exit();
};

for (let i = 0; i < data.length; i++) {
  queue.push(data[i]);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question