


Reuse database connections in routes (or other app) files Note: Following 12-factor methodology, rather than storing connection strings in code you should use config variables. You could also create a module for other application startup tasks such as connecting to third party APIs or loading data or configuration. The initDatabases function call initializes database connections and makes the connections accessible via the dbs variable. Common mistake in connection management for Express appsĪ common mistake developers make when connecting to the database is to call nnect() in every route handler to get a database connection. If your app typically needs more than 5 concurrent connections to the database, you can increase the value of the poolSize setting. The default pool size in the Node driver is 5. When we reuse connections by using a connection pool we avoid this resource cost to the server, and also benefit from lower latency since the app doesn't need to wait for an authentication to finish before a query can be sent. It's important to minimize the frequency and number of new connections to the database because creating and authenticating connections to the database is expensive - these processes require both CPU time and memory. When properly used, connection pools allow you to minimize the frequency of new connections and the number of open connections to your database. After each operation is complete, the connection is kept alive and returned to the pool. What is a connection pool and why is it important?Ī connection pool is a cache of authenticated database connections maintained by your driver, from which your application can borrow connections when it needs to run database operations. You can see a previous version of the code for this example on GitHub. Update : This tutorial has been updated for version 3.0.4 of the mongodb driver.

You can find the code for this example here:

Our example will demonstrate how to create a single connection pool to a MongoDB deployment and how to structure an Express app to reuse that pool across multiple modules. In this post we are going to demonstrate how a production Node.js application might connect to multiple MongoDB databases. However, "getting started" apps generally don't show you how to handle the more serious parts of real-world systems. As a result of its popularity, there are an abundance of tutorials and examples for getting started with new Express apps - we too have created a "getting started" MEAN stack tutorial for the Heroku DevCenter. Express is the most popular Node.js web framework and the fourth most depended-upon package on the NPM registry.
