javascript - MongoDB Error 2nd time calling function: TypeError: Cannot call method 'collection' of null -


i'm using following function add array of documents mongodb collection.

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');             }          });       }    }); } 

the above function works add recipes array mongodb recipes collection. but, when call function twice(30 seconds apart), fails second time following error:

typeerror: cannot call method 'collection' of null 

this because connecting second time isn't working. instead, connect once in more global location , access global connection function.

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');             }          });       }    }); } 

Comments

Popular posts from this blog

c++ - How to add Crypto++ library to Qt project -

jQuery Mobile app not scrolling in Firefox -

How to use vim as editor in Matlab GUI -