Chapter 2. Establishing a Database Connection

We are going to look at the two methods Mongoose uses to connect to databases, mongoose.connect and createConnection. We will also go through various configuration options.

By the end of this chapter, you will understand how to best use the different Mongoose connection methods to meet your needs. We will also have added a connection to the MongoosePM example project.

Mongoose default connection

The way to set the default connection to a MongoDB database via Mongoose is nice and easy, using the mongoose.connect method.

var dbURI = 'mongodb://localhost/mydatabase';
mongoose.connect(dbURI);

This will open a Mongoose connection to the Mongo database mydatabase, running on the server localhost. If established at the correct place in your code, this connection will now be available at any point in your app, if you require Mongoose.

Tip

Best practice

The best practice for a default Mongoose database connection is to open it when the application starts, and keep it open to be re-used. The connection should only need to be closed if your app is being shut down or restarted.

Using multiple connections

The default connection is great if your app only needs to connect to one database. But what happens if you need to connect to a second database at the same time? Or connect to the same database as a different user with different permissions.

For this we can use the mongoose.createConnection method, which is as follows in the code snippet:

var dbURI = 'mongodb://localhost/myadmindatabase';
var adminConnection = mongoose.createConnection(dbURI);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.211.66