Connecting to MongoDB

Now that the mongodb module is installed, we can use it in our experimentation file. Boot up your editor and create a file named test.js. Insert the following block of code into it:

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

MongoClient.connect('mongodb://localhost:27017/mongotest',
(err, db)=>{
console.log('Connected to MongoDB!');
db.close();
});

Executing the preceding code should log Connected to MongoDB! to your screen.

The first thing you'll notice is that we require the mongodb module, but we specifically use the MongoClient component of the module. This component is the actual interface we use to actively open a connection to a MongoDB server. Using MongoClient, we pass the mongodb://localhost:27017/mongotest string URL to our local server as the first parameter. Notice that the path in the URL points to the server and then the name of the database itself.

Remember to make sure you have your local MongoDB server instance running in another terminal for the duration of this chapter. To do so, open a command-line terminal window and execute $ mongod. Your server should launch and log information to the screen, ending with [initandlisten] waiting for connections on port 27017.

You might find that when you run your application, you receive a stack trace error with something like the following code:
events.js:72
thrower; // Unhandled 'error' event
^Error: failed to connect to [localhost:27017]
If this happens, you should realize that it failed to connect to the localhost on port 27017, which is the port that our local mongod server runs under.

Once we have an active connection to our database server, it's as if we are running the Mongo shell command. The MongoClient callback function returns a database connection object (that we named db in our code, but could have named anything), which is exactly the same object we work with in the Mongo shell when we execute use <databasename>. Knowing this, at this point, we can use the db object to do anything we can do via the Mongo shell. The syntax is slightly different, but the idea is generally the same.

..................Content has been hidden....................

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