Is opening a new connection for each query with a MongoDB database good practise?

asynchronous, javascript, mongodb, node.js

Solution

I stumbled upon this on my own research whether to use a new connection for mongodb on each query is the best practice or to use connection pooling. Turns out, that mongodb suggests connection pooling for most use-cases.

Citing from the docs:

A Connection Pool is a cache of database connections maintained by the driver so that connections can be re-used when new connections to the database are required. To reduce the number of connection pools created by your application, we recommend calling MongoClient.connect once and reusing the database variable returned by the callback

I am usually using the following form to establish and reuse a connection while firing queries:

// db.js
import { MongoClient } from 'mongodb';

// this will hold our cached database connection, which will itself hold multiple connections in a pool to be used
let connection,
  database;

export {
  connect: (next) => {
    // already established? => return connection
    if (database) return next(undefined, database);

    // establish connection
    MongoClient.connect('http://localhost:27017/admin', (err, db) => {
      if (err) return next(err);

      // save connection
      connection = db;

      // connect to database
      database = db.db('myDatabase');

      // call callback
      next(undefined, database);
    });
  },

  disconnect: (next) => {
    if (!connection) return next();

    // close connection
    connection.close();
    next();
  }
};

Firing queries:

import db from './db';

db.connect((err, db) => {
  if (err) return next(err);

  db.collection('myUsers').insertOne({name: 'test'}, (err) => {
    if (err) throw err;

    db.disconnect((err) => {
      if (err) throw err;

      console.log('Everything finished, database connection closed');
    });
  });
});

Note: It is possible to determine the maximum amount of pooled connections manually (afaik the default is 5?). Refer to the docs about how to set the amount of opened connections via the mongodb url.

Problem

I'm creating a web server that stores a user's data in a MongoDB database. The code behind the web requests uses asynchronous functions to insert a document into the database, but because these functions are asynchronous it means that for every request a new connection is made with the server. ``` exports.create_user = function(username, password, callback) { mongo.connect(url, function(err, db) { db.collection('users').insertOne({username: username, password: password}, function(err, result) { callback(result) db.close() }) }) } ``` I'm under the impression that doing it this way is not the best practise, but I can't think a way to do it using the module model that I'm using above. Any suggestions or advice would be appreciated.

Original source