mongo 数据库连接问题 "Cannot call method 'update' of undefined"

mongo db connection issue "Cannot call method 'update' of undefined"

我已经按照这段代码设置了 mongoldb 连接

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

稍后在代码中,我将文档更新为一个函数内的集合,该函数按时间间隔重复

setInterval(create_doc,db_doc_interval);

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

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

问题是它给出了一个错误

TypeError: Cannot call method 'update' of undefined

这让我觉得集合没有被正确定义或者没有被正确传递到函数中。任何帮助是极大的赞赏。谢谢

顺便说一句,如果我将建立连接部分放在调用集合的第二个函数中,代码就可以正常工作。但这会导致每次都建立一个新连接并且非常耗费资源

此错误是由于 collection 变量未在 client.connect 的回调函数中分配,然后在 create_doc 函数中通过访问 [=14= 调用它之前] 功能。将 setInterval 函数移动到 client.connect( 的回调中,如下所示。

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