繁体   English   中英

MongoDB错误第二次调用函数:TypeError:无法调用null的方法“ collection”

[英]MongoDB Error 2nd time calling function: TypeError: Cannot call method 'collection' of null

我正在使用以下功能将文档数组添加到MongoDB集合中。

function recipesToDB(recipes) {
   mongo.connect(uristring, function (err, db) {
      if (err) {
         console.log ('ERROR connecting to: ' + uristring + '. ' + err);
      } else {
         console.log ('Succeeded connected to: ' + uristring);

         db.createCollection('recipes', function(err, collection) {});

         var collection = db.collection('recipes');

         collection.insert(recipes, {continueOnError: true}, function(err, result) {
            if (err) {
               console.log('ERROR:' + err);
            } else {
               console.log('success');
            }
         });
      }
   });
}

上面的函数可以将我的食谱数组添加到MongoDB食谱集合中。 但是,当我两次调用该函数(相隔30秒)时,该函数第二次失败,并出现以下错误:

TypeError: Cannot call method 'collection' of null

如果mongodb有mongod.lock,应该出现此错误,这是删除mongod.lock的方法: sudo rm mongod.lock ,必须重新启动mongodb之后,即sudo服务mongod restart

这可能是因为第二次连接不起作用。 而是在更全局的位置连接一次,然后从此功能访问全局连接。

var mongoDb;
function connectToDb(done){
  mongo.connect(uristring, function (err, db) {
      if (err) {
         console.log ('ERROR connecting to: ' + uristring + '. ' + err);
      } else {
         console.log ('Succeeded connected to: ' + uristring);
         mongoDb = db;
         done();
      }
  }
}

connectToDb(function(){
   recipesToDB(yourRecipesObject);
});


function recipesToDB(recipes) {


         mongoDb.createCollection('recipes', function(err, collection) {});

         var collection = mongoDb.collection('recipes');

         collection.insert(recipes, {continueOnError: true}, function(err, result) {
            if (err) {
               console.log('ERROR:' + err);
            } else {
               console.log('success');
            }
         });
      }
   });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM