使用node.js将多个文档插入Mongodb

时间:2014-09-01 10:55:55

标签: javascript node.js mongodb mongoose mongodb-query

我正在尝试使用node.js向我的数据库插入多个文档,问题是我收到错误: MongoError:应用程序关闭了连接 有任何选项可以并行插入多个文档吗?

这是我的代码:

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

3 个答案:

答案 0 :(得分:3)

在MongoDB 3.2及以上版本中,您可以使用db.collection.insertMany()将多个文档保存到集合中。 ( enter image description here

您的代码可以简化为:

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

答案 1 :(得分:0)

"async"库帮助你在这里,因为你需要理解异步代码中的“回调”,这对你有帮助的主要是“代码蠕变”,因为它不需要“缩进”每个“下一个”调用在代码中。

事实上,您可以在"parallel"而不是"series"执行这些操作,以进行合理的操作。我们只需要“等待”每个人完成,这就是“回调”的目的。它“回调”以在操作完成时调用“下一个动作”:

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

每个操作现在等待它的“回调”从它自己的“回调”上下文中调用,并且有“流量控制”等到所有操作完成后才最终“关闭” “所有操作结束时的连接。

但如前所述,除非这是一个“一次性”脚本,否则您基本上从不在数据库连接上调用.close(),而您只需打开一次

答案 2 :(得分:0)

您可以使用mongo批量插入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();