Mongoose Connection best practice

There is often quite a lot of confusion about how best to set up a database connection with Mongoose. So I thought I’d clear it up!

There are two ways of establishing a Mongoose connection, using the default connection or a named connection. In this article we’ll be looking at using the default connection.

Let’s start with a list of things we want to achieve:

Open the connection when the app starts

Monitor the connection events

Close the connection when the app process terminates

Define a schema and build a model that we can use in the app

Defining the Node.js app

Let’s define a really simple skeleton Node.js app, using the following file structure.

app.js
pages.js
model/
- db.js
- team.js

app.js will be the starting point of the application, creating the server and tying everything together. pages.js will contain a rudimentary controller to interact with Mongoose and display output to a browser window model/db.js will hold the database connection and event listeners model/team.js will hold a Mongoose schema definition

Starting with app.js, we need to require the HTTP module, the db file and the pages file. We’ll also create a server that listens to the localhost port of 8888, serving an index page that we will define later in pages.js.

Managing the Mongoose connection

Our model/db.js file is where we’ll hold the database connection information and event handlers. We’ll also import our schemas & models into here so that the application has access to them. The comments in the code should make it pretty obvious what’s going on here.

Using the Mongoose connection

Finally, we want to do something with the connection. So in pages.js we want the following code. What we’re going to do is require Mongoose, bring the Team model in, create a new team and output it to the browser window.

Running the test page

So there we go. As you can see it’s pretty straightforward to create a default Mongoose connection and use it in your application. You can test the disconnection script and event handler by terminating your Node process. In the terminal window running the Node app just hit Ctrl + C to kill the process.