【问题标题】:How to store a reference to a MongoDB connection in a variable?如何在变量中存储对 MongoDB 连接的引用?
【发布时间】:2021-04-27 19:22:04
【问题描述】:

我对 Node.js 的 MongoDB 驱动程序的异步实现有点问题。

在文档示例中,连接发生如下:

const client = new MongoClient(uri, ...);

async function run() {

  try {
    await client.connect();
    const coll = client.db('locations').collection('streets');
    
    coll.find({...});
    
  } catch {
  
    ...
    
  } finally {
  
    client.close();
    
  }
  
}

run().catch(console.dir);
    
    

但是假设我想在对象中使用连接,而不是在需要连接时为每种情况创建一个函数。例如,我想创建一个允许我将 cmets 插入数据库的对象:

const Comments = {
  connection: /* how would I put a MongoDB connection here when it's async? */,
  commentsCollectionRef: /* how would I put a collection reference here? */
  add: function(user, comment) {
          collectionRef.insertOne({user, comment});
  }
};

/* And to use the object like this to insert comments: */
Comment.add("Martin", "hello");
Comment.add("Julie", "hi");
Comment.add("Mary", "hello");
  
   

想必,这样的事情是不可能的:

async function connect() {

  await client.connect();
  
}

const Comments = {

  connection: connect() /* this returns a promise, but you can't store a reference to its value like this */
  
  ...
}

拥有一个每次连接并关闭连接的功能真的是 MongoDB 的唯一选择吗?

谢谢

【问题讨论】:

    标签: javascript node.js mongodb asynchronous nosql


    【解决方案1】:

    您不必每次调用数据库时都打开新连接。您可以简单地使用连接状态保留一个单独的变量。 比如:

    const client = new MongoClient(uri, ...);
    let connected = false;
    
    async function connnect() {
      if(!connected) {
        await client.connect();
        connected = true;
      }
    }
    
    async function disconnect() {
      if(connected) {
        await client.close();
        connected = false;
      }
    }
    
    // All other comment specific code next...

    然后您可以围绕此构建您的库。 对于与数据库交互的每个方法,请先调用 connect。 或者在启动应用时调用connect,在退出时调用disconnect

    但是,如果您要拥有表示数据库集合的对象,我建议您查看Mongoose。您可以轻松定义模型,它可以让您的生活更轻松。

    【讨论】:

      猜你喜欢
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-01
      • 2016-07-29
      • 1970-01-01
      • 2019-06-29
      • 1970-01-01
      相关资源
      最近更新 更多