如何在整个应用程序中使用相同的 mongodb 连接?

How can I use the same mongodb connection throughout the app?

我正在尝试这种方法,但我不确定是否每次都会创建一个新连接。

getMongoClient.js

const { MongoClient } = require('mongodb');
const serverURL = process.env['mongoServerURL']

module.exports = async function (){

    const mongoClient = await new MongoClient(serverURL);
    await mongoClient.connect();
    return mongoClient;
}

然后在 app.js

const getMongoClient = require("./_helpers/getMongoClient.js")
module.exports = getMongoClient();

然后在数据库中service.js

async function syncGuilds(client){

    const mongoClient = await require("../app.js")
     ... some database operations
}
module.exports = syncGuilds

节点模块本身是单例的,你不需要担心它们。一旦你的模块被评估,它就不会被再次评估。因此,您将始终收到模块的相同实例,即它不会创建 mongo 连接的多个实例。

您可以查看 this and this link 了解更多详情。

它不会每次都创建一个新的连接,如果你想你可以在选项中指定最大连接池大小默认值是5。检查下面link

https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#connection-pool-configuration

const mongodb = require("mongodb");
let client = new mongodb.MongoClient(
  "url",
  {
    tls: true,
    auth: { user: "myuser", password: "mypassword" },
    useNewUrlParser: true,
    useUnifiedTopology: true,
    poolSize: 1,
    maxPoolSize: 1,
  }
);