Advanced Node.js Development
上QQ阅读APP看书,第一时间看更新

Connecting the mongodb-connect file to the database

With MongoDB now installed, we can move it to our mongodb-connect file and start connecting to the database. The first thing we need to do is pull something out of the library that we just installed, which is the mongodb library. What we're looking for is something called the MongoClient constructor. The MongoClient constructor lets you connect to a Mongo server and issue commands to manipulate the database. Let's go ahead and kick things off by creating a constant called MongoClient. We're going to set that equal to require, and we're going to require the library we just installed, mongodb. From that library, we're going to pull off MongoClient:

const MongoClient = require('mongodb').MongoClient; 

With the MongoClient now in place, we can call MongoClient.connect to connect to the database. This is a method, and it takes two arguments:

  • The first argument is a string, and this is going to be the URL where your database lives. Now in a production example, this might be an Amazon Web Services URL or a Heroku URL. In our case, it's going to be a localhost URL. We'll talk about that later.
  • The second argument is going to be a callback function. The callback function will fire after the connection has either succeeded or failed, and then we can go ahead and handle things appropriately. If the connection failed, we'll print a message and stop the program. If it succeeded, we can start manipulating the database.