【问题标题】:Inserting multiple documents to Mongodb using node.js使用 node.js 将多个文档插入到 Mongodb
【发布时间】:2017-06-27 19:28:17
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • 您需要阅读“异步”代码。在所有其他操作完成之前调用.close()。这些操作不一定按顺序“完成”。查看"async" 作为节点库,了解如何按照您的意图在“系列”中清楚地执行此操作。不过一般来说,您几乎从不真的想明确地关闭数据库连接,除非您真的完成了。
  • 你能给我一些代码示例吗?

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


【解决方案1】:

在 MongoDB3.2 及更高版本中,您可以使用 db.collection.insertMany() 将多个文档保存到一个集合中。 (see documentation)

您的代码可以简化为:

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

【讨论】:

    【解决方案2】:

    "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(),并且您只打开它一次

    【讨论】:

    • 有人会认为所有的 sql 都不会完全相同。但 firebase 数据库略有不同,就像英国和美国的巨无霸不同...
    【解决方案3】:

    你可以使用 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();
    

    【讨论】:

      猜你喜欢
      • 2013-02-15
      • 2013-12-13
      • 2017-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 2017-04-07
      • 2018-09-20
      相关资源
      最近更新 更多