1

I'm trying to insert multiple documents to my DB using node.js , the thing is that i'm getting an error: MongoError: Connection closed by application There is any option to insert multiple documents in parallel?

Here is my code:

var MongoClient = require('mongodb').MongoClient;



var dbName = "tst1";
var port = "27017";
var requiredCollection = "stocks"
var host = "localhost";

// open the connection the DB server

MongoClient.connect("mongodb://" + host + ":" + port + "/" + dbName, function (error, db){

    console.log("Connection is opened to : " + "mongodb://" + host + ":" + port + "/" + dbName);

    if(error) throw error;

        var ibm = {'_id' : 1, 'value' : 1, 'ticker' : 'IBM'};

        db.collection(requiredCollection).insert(ibm, function(error, inserted) {
            if(error) {
                console.error(error);

            }
            else {
                console.log("Successfully inserted: " , inserted );
            }

        }); // end of insert


        var apple = {'_id' : 2, 'vlue' : 1, 'ticker' : 'AAPL'};

        db.collection(requiredCollection).insert(apple, function(error, inserted) {
            if(error) {
                console.error(error);

            }
            else {
                console.log("Successfully inserted: " , inserted );
            }

        }); // end of insert





        var intel = {'_id' : 3, 'value' : 1, 'ticker' : 'INTC'};

        db.collection(requiredCollection).insert(intel, function(error, inserted) {
            if(error) {
                console.error(error);

            }
            else {
                console.log("Successfully inserted: " , inserted );
            }

        }); // end of insert


        var f5 = {'_id' : 4, 'value' : 1, 'ticker' : 'FFIV'}; 

        db.collection(requiredCollection).insert(f5, function(error, inserted) {
            if(error) {
                console.error(error);

            }
            else {
                console.log("Successfully inserted: " , inserted );
            }

        }); // end of insert




        var arris = {'_id' : 5, 'value' : 1, 'ticker' : 'ARRS'};

        db.collection(requiredCollection).insert(arris, function(error, inserted) {
            if(error) {
                console.error(error);

            }
            else {
                console.log("Successfully inserted: " , inserted );
            }

        }); // end of insert

        db.close();





}); // Connection to the DB
2
  • 1
    You need to read up on "asynchronous" code. The .close() is being called before all the other operations complete. The operations do not "complete" in order necessarily. Take a look at "async" as a node library for examples of how to clearly do this in "series" as you intend. Generally speaking though, you almost never really want to explicitly close your database connection unless you are truly done. Commented Sep 1, 2014 at 11:17
  • can you give me some code example? Commented Sep 1, 2014 at 11:20

3 Answers 3

5

In MongoDB version 3.2 and above, you can use db.collection.insertMany() for saving multiple documents into a collection. (see documentation)

Your code can be simplified to:

var MongoClient = require('mongodb').MongoClient;

var dbName = "tst1";
var port = "27017";
var requiredCollection = "stocks"
var host = "localhost";

// open the connection the DB server

MongoClient.connect("mongodb://" + host + ":" + port + "/" + dbName, function (error, db){

    console.log("Connection is opened to : " + "mongodb://" + host + ":" + port + "/" + dbName);

    if(error) throw error;

        var docs = [{ _id: 1,  value: 1,  ticker: 'IBM' },
                    { _id: 2,  value: 1,  ticker: 'AAPL' },
                    { _id: 3,  value: 1,  ticker: 'INTC' },
                    { _id: 4,  value: 1,  ticker: 'FFIV' },
                    { _id: 5,  value: 1,  ticker: 'ARRS' }];

        db.collection(requiredCollection).insertMany(docs, function(error, inserted) {
            if(error) {
                console.error(error);
            }
            else {
                console.log("Successfully inserted: " , inserted );
            }

        }); // end of insert

        db.close();

}); // Connection to the DB
Sign up to request clarification or add additional context in comments.

Comments

1

The "async" library helps you here as you need to understand "callbacks" in asynchronous code and the main thing this helps you with is "code creep" by removing the need to "indent" each "next" call in code.

In fact you can do these in "parallel" rather than "series" for a reasonable amount of operations. We just need to "wait" for each to complete, which is what a "callback" is for. It "calls back" to invoke the "next action" when the operation is complete:

var MongoClient = require('mongodb').MongoClient,
    async = require('async');

var dbName = "tst1";
var port = "27017";
var requiredCollection = "stocks"
var host = "localhost";

// open the connection the DB server

MongoClient.connect("mongodb://" + host + ":" + port + "/" + dbName, function (error, db){

    console.log("Connection is opened to : " + "mongodb://" + host + ":" + port + "/" + dbName);

    if(error) throw error;

    async.parallel(
      [        
        function(callback) {      
          var ibm = {'_id' : 1, 'value' : 1, 'ticker' : 'IBM'};

          db.collection(requiredCollection).insert(ibm, function(error, inserted) {
            if(error) {
              console.error(error);
              callback(error);
            } else {
              console.log("Successfully inserted: " , inserted );
              callback();
            }
          }); // end of insert
       },
       function(callback) {
         var apple = {'_id' : 2, 'vlue' : 1, 'ticker' : 'AAPL'};

         db.collection(requiredCollection).insert(apple, function(error, inserted) {
           if(error) {
             console.error(error);
             callback(error);
           } else {
             console.log("Successfully inserted: " , inserted );
             callback();
           }
         }); // end of insert
       },
       function(callback) {    
         var intel = {'_id' : 3, 'value' : 1, 'ticker' : 'INTC'};

         db.collection(requiredCollection).insert(intel, function(error, inserted) {
           if(error) {
             console.error(error)
             callback(error);
           } else { 
             console.log("Successfully inserted: " , inserted );
             callback();
           }
        }); // end of insert
      },
      function(callback) {    
        var f5 = {'_id' : 4, 'value' : 1, 'ticker' : 'FFIV'}; 

        db.collection(requiredCollection).insert(f5, function(error, inserted) {
          if(error) {
            console.error(error);
            callback(error);
          } else {
            console.log("Successfully inserted: " , inserted );
            callback();
          }
        }); // end of insert
      },
      function(callback) { 
        var arris = {'_id' : 5, 'value' : 1, 'ticker' : 'ARRS'};

        db.collection(requiredCollection).insert(arris, function(error, inserted) {
          if(error) {
            console.error(error)
            callback(error);
          } else {
            console.log("Successfully inserted: " , inserted );
          }
        }); // end of insert
      },
    ],
    function(err) {
      // called when everything is done
      db.close();
    }    
  );
}); // Connection to the DB

Each operation now waits for it's "callback" to be called from it's own "callback" context as well as there being the "flow control" to wait until all operations have completed before finally "closing" the connection at the end of all operations.

But as said earlier, unless this is a "one off" script you basically never call .close() on the database connection and you only ever open it once.

1 Comment

One would think that all no sql would be identical.. but firebase database is slightly different just like big macs are different in england and america...
0

you could use mongo bulk insert https://docs.mongodb.com/manual/reference/method/Bulk.insert/

var bulk = db.items.initializeUnorderedBulkOp();
bulk.insert( { item: "abc123", defaultQty: 100, status: "A", points: 100 } );
bulk.insert( { item: "ijk123", defaultQty: 200, status: "A", points: 200 } );
bulk.insert( { item: "mop123", defaultQty: 0, status: "P", points: 0 } );
bulk.execute();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.