Connecting to the MongoDB database
All operations to access MongoDB require establishing a connection with it. Now let’s see how to establish a connection with MongoDB.
The mongoose.connect(url) instruction connects the mongoose module to the database specified in the url parameter. The url parameter is of the form "mongodb://localhost/mydb_test" to connect to the mydb_test database on the localhost server.
The database will actually be created (and visible with the execution of the show dbs command of the mongo utility) when the first document is inserted into it:
Connecting to the mydb_test database (test.js file)
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/mydb_test");
console.log("Connecting to mydb_test database in progress...");
Let’s run the previous program:
Figure 8.3 – Database connection
To know whether the connection to the database has actually...