WittCode💻

Connect Node to MongoDB

By

Learn how to connect a Node application to MongoDB. Specifically, we will use the npm package mongodb to connect to and query a MongoDB server.

Table of Contents 📖

Initializing a Node Project

If we want to add persistence to a Node application we can use the NoSQL database MongoDB. To begin, lets initialize our project as an ES6 npm project.

npm init es6 -y

Now, to connect a Node application to MongoDB, we need a MongoDB driver. A MongoDB driver is essentially software that manages connecting to MongoDB. We can install it from npm.

npm i mongodb

Connecting to MongoDB

Now that we have our driver installed, we need to create a MongoClient from this package and give it a connection URI.

import {MongoClient} from 'mongodb';

const URI = 'mongodb://localhost:27017';
const client = new MongoClient(URI);

A connection URI is a URI that contains the connection information to connect a MongoClient to a Mongo server. Its syntax consists of a protocol, a host, and a port.

  • The protocol is mongodb.
  • The location of the server is localhost as it is running on our local computer.
  • The default port that MongoDB runs on is 27017.

If the server requires authentication, then we need to supply our authentication credentials to this URI as well.

const URI = 'mongodb://username:password@localhost:27017';

Now, to connect to the database, we use the connect method on the the MongoClient.

client.connect()
  .then(() => {
    console.log('Connected to MongoDB');
  })
  .catch(err => {
    console.error('Something went wrong', err);
  });

This method will return a promise that will resolve when the connection is established and will reject if there is an error connecting.

Querying MongoDB

Now that we're connected, lets query MongoDB. Remember, Mongo creates a database and collection automatically when data are first stored in them.

const db = client.db('myCoolDB');
const collection = db.collection('myCoolCollection');

client.connect()
  .then(() => {
    console.log('connected');
    return collection.insertOne({hello: 'world'});
  })
  .then(result => {
    console.log('Inserted data', result);
    return collection.findOne();
  })
  .then(result => {
    console.log('Retrieved data', result);
  })
  .catch(err => {
    console.error('Something went wrong', err);
  })
  .finally(() => {
    client.close();
  });
  • Find the database called myCoolDB. A database stores one or more collections.
  • Find the collection called myCoolCollection. A collection stores one or more documents.
  • Insert an object into the collection using insertOne. This function will create both the database and collection if they do not exist.
  • Get one document using findOne and log it to the console.
  • Close the connection to MongoDB using client.close.
Connect Node to MongoDB