1

i have set up a mongoldb connection as in this code

client.connect(mongodbURL,function (err,db){
   if(err) throw err;
   collection=db.collection("accel1");
 });

later in the code, i update documents to a collection inside a function that is repeated in intervals

setInterval(create_doc,db_doc_interval);

 function create_doc(){
 console.log("writing to db");

 collection.update( <...updates> );
 }

the problem is it gives an error

TypeError: Cannot call method 'update' of undefined

which makes me think that somehow collection is not being defined correctly or it is not being passed into the function correctly. any help is greatly appreciated. thanks

BTW code works fine if i put the establishing connection part inside the second function were collection is called. but this causes a new connection to be established every time and is very resource intensive

1 Answers1

0

This error is caused by the collection variable is NOT be assigned in the callback function of client.connect, before it is invoked in the create_doc function through accessing .update function. Move setInterval function into the callback of client.connect( as below.

client.connect(mongodbURL,function (err,db){
     if(err) throw err;
     collection=db.collection("accel1");
     setInterval(create_doc,db_doc_interval);
 });
zangw
  • 43,869
  • 19
  • 177
  • 214