如何在变量中存储对 MongoDB 连接的引用?

How to store a reference to a MongoDB connection in a variable?

我对 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);
    
    

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

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 的唯一选择吗?

谢谢

您不必在每次调用数据库时都打开一个新连接。您可以简单地保留一个包含连接状态的单独变量。 类似于:

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 并在退出时调用 disconnect

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