/bio/skills/blog/math

Get that Mongoose

In general, in a MongoDB production environment using Mongoose, the driver should automatically reconnect to the database when it loses its connection. Mongooses documentation mentions this here.

There is, however, an important exception. When running tests. We often need to close all sockets before our tests will exit (process.exit(0) is a dirty hack around this; use wtfnode to find what connections are still open that keep your tests hanging). And you may find you want to disconnect in one test and reconnect later in another test. This is one instance that

mongoose.connect(mongoConnectionUrl, {user, password, authSource, autoReconnect: false}

will be a useful connection string.

Make sure NOT to use it in your production environment. I recommend putting this connection is your test helpers and using that connection in your tests only.

2025 Stefano De Vuono