13

I have A Mongoose Connection and at some point in my program I need to close it. after logging the mongoose object several times, I have found that the following workd

mongoose.connection.base.connections[1].close();

Is There A Cleaner way to do this?

mkoryak
  • 57,086
  • 61
  • 201
  • 257
Ari Porad
  • 2,834
  • 3
  • 33
  • 51

2 Answers2

48

To close all connections in the Mongoose connection pool:

mongoose.disconnect();

Docs here.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
0

I used a singleton in my code.

Exporting a promise

In one file I export a promise...

connection.js

const { createConnection } = require('mongoose');

function getConnection() {
  return mongoose.createConnection(...).asPromise();
}
const connPromise = getConnection();
module.exports = connPromise;

other files...

const connPromise = require('./connection.js');

async function handler() {
  // Connection starts on first module import
  // This gets faster when the connection is done being created
  const connection = await connPromise;
  // Do stuff with the connection
  return {
    data: '',
    and: '',
    stuff: '',
  };
}

When everything is shutting down, like in a lambda, also in connection.js:

process.on('SIGTERM', async () => {
  console.info('[runtime] SIGTERM received');
  const conn = await connPromise;
  await conn.close();
  console.info('[runtime] closed connection');
  process.exit(0);
});

So by storing the connection in a promise, I can get it everywhere. I don't export the connection itself because getting it is async.

Exporting a getter function

I could have a function like

let connection = null;
function getConnection() {
  if (!connection) {
    connection = await createConnection(...).asPromise();
  }
  return connection;
}

module.exports = getConnection;

other files...

const getConnection = require('./connection.js');

async function handler() {
  // Gets faster after the first call.
  // connection created on first call.
  const connection = await getConnection();
  // Do stuff with the connection
  return {
    data: '',
    and: '',
    stuff: '',
  };
}

Then your shutdown would become

process.on('SIGTERM', async () => {
  console.info('[runtime] SIGTERM received');
  if (connection) {
    await connection.close();
    console.info('[runtime] closed connection');
  }
  process.exit(0);
});

Summary

Overall, I like exporting the promise, since in every lambda function, I'm always using the database.

Since the exported promise means that the connection starts as soon as the module is imported, it's ready to go sooner than if I waited till the invocation of the getConnection() in an event handler.

For having only one connection, this is a good way to get ahold of it.

LSOJ
  • 51
  • 5