Connecting to a MongoDB database by using Mongoose is very similar to using the connection string method discussed in Chapter 13, “Getting Started with MongoDB and Node.js.” It uses the connection string format and options syntax shown below:
connect(uri, options, [callback])
Note
The Mongoose library must be installed using npm install mongoose
to be able to use it in your Node.js applications.
The connect()
method is exported at the root level of the mongoose
module. For example the following code connects to the words
database on the localhost
:
var mongoose = require('mongoose'),
mongoose.connect('mongodb://localhost/words'),
The connection can be closed using the disconnect()
method of the mongoose
module. For example:
mongoose.disconnect();
Once created, the underlying Connection
object can be accessed in the connection
attribute of the mongoose
module. The Connection
object provides access to the connection, underlying Db
object, and Model
object that represents the collection. This gives you access to all the Db
object functionality described in Chapter 13. For example, to list the collections on the database, you could use the following code:
mongoose.connection.db.collectionNames(function(err, names){
console.log(names);
});
The Connection
object emits the open
event, which you can use to wait for the connection to open before trying to access the database. To illustrate the basic life cycle of a MongoDB connection via Mongoose, the code in Listing 16.1 imports the mongoose
module, connects to the MongoDB database, waits for the open
event, displays the collections in the database, and disconnects. The output is shown in Figure 16.1.
1 var mongoose = require('mongoose'),
2 mongoose.connect('mongodb://localhost/words'),
3 mongoose.connection.on('open', function(){
4 console.log(mongoose.connection.collection);
5 mongoose.connection.db.collectionNames(function(err, names){
6 console.log(names);
7 mongoose.disconnect();
8 });
9 });