admin管理员组

文章数量:1357374

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

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
Share Improve this question edited Jun 27, 2017 at 11:28 Neil Lunn 151k36 gold badges355 silver badges325 bronze badges asked Sep 1, 2014 at 10:55 Alex BrodovAlex Brodov 3,52521 gold badges47 silver badges70 bronze badges 2
  • 1 You need to read up on "asynchronous" code. The .close() is being called before all the other operations plete. The operations do not "plete" 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. – Neil Lunn Commented Sep 1, 2014 at 11:17
  • can you give me some code example? – Alex Brodov Commented Sep 1, 2014 at 11:20
Add a ment  | 

3 Answers 3

Reset to default 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

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 plete, which is what a "callback" is for. It "calls back" to invoke the "next action" when the operation is plete:

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 pleted 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.

you could use mongo bulk insert https://docs.mongodb./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();

本文标签: javascriptInserting multiple documents to Mongodb using nodejsStack Overflow