Home > Net >  How can I use the same mongodb connection throughout the app?
How can I use the same mongodb connection throughout the app?

Time:12-15

I'm trying this approach, but I'm not sure if that creates a new connection every time.

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;
}

then in the app.js

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

then in a database service.js

async function syncGuilds(client){

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

CodePudding user response:

Node modules are singleton by themselves, you don't need to worry about them. When your modules is once evaluated, it won't be evaluated again. So you will always receive same instance of the module i.e it won't create multiple instance of mongo connection.

You can check this and this link for more details.

CodePudding user response:

It won't create a new connection every time, If you want you can specify max connection pool size in options default value is 5. Check below 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,
  }
);
  • Related