Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

nodejs mongodb native reuse single connection

require('dotenv').config();
const { MongoClient } = require('mongodb');
const config = require('../../config/index');

const username = encodeURIComponent(config.mongo_db1.user);
const password = encodeURIComponent(config.mongo_db1.pass);
const dbHost = config.mongo_db1.host;
const authMechanism = 'DEFAULT';
const qString = `retryWrites=true&w=majority&authMechanism=${authMechanism}`;

const uri = `mongodb+srv://${username}:${password}@${dbHost}/?${qString}`;

const mongoOptions = {
  poolSize: 100,
  wtimeout: 2500,
  useNewUrlParser: true,
  useUnifiedTopology: true,
};

const client = new MongoClient(uri, mongoOptions);

let _db;

client.on('serverClosed', (event) => {
  // eslint-disable-next-line no-console
  console.log('received serverClosed');
  // eslint-disable-next-line no-console
  console.log(JSON.stringify(event, null, 2));

  // should i call mongoDBConnection() here if connection lost while app running?
});

const mongoDBConnection = async (app) => {
  try {
    if (client.isConnected()) {
      _db = client.db(config.mongo_db1.dbName);
      return client.db(config.mongo_db1.dbName);
    }

    await client.connect();
    if (app) app.use(passport.initialize());
    _db = client.db(config.mongo_db1.dbName);
    return client.db(config.mongo_db1.dbName);
  } catch (error) {
    return Promise.reject(error);
  }
};

const dbObj = () => _db;

module.exports = {
  mongoDBConnection,
  dbObj,
};
Source by www.mongodb.com #
 
PREVIOUS NEXT
Tagged: #nodejs #mongodb #native #reuse #single #connection
ADD COMMENT
Topic
Name
8+7 =