【问题标题】:How to use the MongoClient without coding "client.close()" every time? [duplicate]如何使用 MongoClient 而无需每次都编写“client.close()”? [复制]
【发布时间】:2019-10-26 03:15:38
【问题描述】:

我尝试打包数据库连接以获得更多可重用性。 我想达到这样的目标:

const mongoPromise =MongoClient.connect(url,{ useNewUrlParser: true })
.then((client)=>{
      const db = client.db(dbName);

      // do something...

      client.close();
})
.catch(err=>console.log(err));

因此,我可以在其他地方使用它:

//For example
//query
mongoPromise.then((db)=>db.collection('user').find().toArray())

//insert
mongoPromise.then((db)=>db.collection('test').insert({...}))

查询或插入完成后,MongoClient 将关闭


第一种方法,我可以通过混合回调和承诺来找出解决方案。

callback和promise混在一起不好吗?

// First method
const mongoPromiseCallback =(callback)=>MongoClient.connect(url,{ useNewUrlParser: true })
.then(async(client)=>{
      const db = client.db(dbName);
      await callback(db);
      console.log("close the client");
      client.close();
})
.catch(err=>console.log(err))

mongoPromiseCallback(db=>db.collection('user').find().toArray())
.then(res=>console.log(res)));


在另一种方法中,我尝试仅使用承诺,但我不知道 我在哪里可以关闭客户端

// the other method
const mongoPromise =MongoClient.connect(url,{ useNewUrlParser: true })
.then((client)=>{
      const db = client.db(dbName);
      return new Promise(function(resolve, reject) {
        resolve(db);
      });
})
.catch(err=>console.log(err));

mongoPromise.then(db=>db.collection('user').find().toArray())
.then(res=>console.log("res"));

【问题讨论】:

    标签: javascript node.js mongodb promise callback


    【解决方案1】:

    您始终可以重用您在 mongo.xml 中创建的 db 对象。在这里阅读它将回答问题How do I manage MongoDB connections in a Node.js web application?

    【讨论】:

    • 哦!非常感谢。我使用 MongoDB 出错了。但是,如果它不在mongoDB中而是在常见情况下,我仍然想知道如何修复它。
    • 在这种情况下,使用连接池
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    相关资源
    最近更新 更多