Select Page

The first part of the Quick Start series I wrote some time ago. Today it’s a little bit outdated so I recommend you to check my YouTube video where I show how to configure VS Code to creating the node.js applications with Typescript.

In this post, I’d like to continue the Quick Start series and show you how to connect to a MongoDB database from node.js.

Before we start writing code we need to be able to connect to a MongoDB server. We have 3 options:

  • Installing the MongoDB Community Edition server on your local machine
  • Running the server with the official MongoDB Docker image
  • Registering on MongoDB Atlas which offers MongoDB as service and allows you testing a basic replica set for free. It’s worth mentioning that MongoDB Atlas allows you to select on which cloud provider your database server would be running. For now, 3 cloud providers are available: AWS, Google Cloud Platform, Microsoft Azure.

Feel free to choose an option which is the most convenient for you. From the code perspective, it doesn’t really matter where you are going to connect. If you’re not familiar with Docker or you don’t want to install any additionals tools on your local machine, free plan on MongoDB Atlas seems to be the best option.

Installing packages

Once your MongoDB server is ready and running we may write some code. At the beginning, we need to install two npm’s packages. The first one is mongodb which contains a native node.js driver for MongoDB. To install it run the below command:
npm install mongodb --save
and then the second for type definitions:
npm install @types/mongodb –save-dev

Storing database connection in a singleton object

In order to avoid connecting every time to MongoDB before querying a database, we are going to store the opened connection in the singleton object. Let’s create a new file DbClient.ts and save it in the common folder. The singleton class will look like this:

import { MongoClient, Db } from "mongodb";

class DbClient {
    public db: Db;

    public connect() { /* ... */ }
}

export = new DbClient();

In the first line, we imported MongoClient and Db types from mongodb package. The DbClient class contains a single method connect() where we will connect to the MongoDB database and then save the connection as a class member. In the last line, we export a new instance of the DbClient class. That instance will be returned every time when we use/load the DbClient by calling import DbClient = require(“../common/DbClient”);

Connecting to a database – callback approach

Now let’s add utilise the MongoClient and connect to a database. By default MongoClient allows you to pass a callback function as the last argument which would be called when the connection is established or when an error occurs.

MongoClient.connect("mongodb://localhost:27017/test", (err, db) => {
     if(err) {
         console.log(err);
     } else {
         this.db = db;
     } 
 });

Connecting to a database – promise approach

You may also skip passing the callback function and then MongoClient will return a new Promise.

return MongoClient.connect("mongodb://localhost:27017/test")
    .then(db => {
        this.db = db;
    })
    .catch(err => {
        console.log(err);
    });

Connecting to a database – async/await approach

From Typescript 2.1 you may also use async/await approach – even if you need to transpile your TypesScript code to ES5 or ES3 version of Javascript. You can read more about async/await in Typescript in TypeScript Deep Dive online book and Marius Schulz’s blog (BTW. I recommend adding both those sites to your bookmarks!).

try {
    this.db = await MongoClient.connect("mongodb://localhost:27017/test");
    console.log("Connected to db");
    return this.db;
} catch (error) {
    console.log("Unable to connect to db");
}

Utilising DbClient

DbClient is ready to use. In the main application file app.ts let’s import it by calling import DbClient = require("./common/DbClient");and then we can try to connect to a database and run basic queries:

try {
    let db = await DbClient.connect();

    let results = await db.collection("todo").insertOne({
        topic: "learn angular.js", progress: 10
    });

    console.log(results.insertedId);

    let results2 = await db.collection("todo").insertMany([
        {  topic: "learn typescript", progress: 10 },
        {  topic: "learn node.js", progress: 10 }
    ]);

    console.log(results2.insertedIds);

    let docs = await db.collection("todo").find().toArray();

    console.log(docs);
} catch (error) {
    console.log("Unable to connect to db");
}

Please note that database doesn’t have to exist on the MongoDB server. It will be created automatically by the MongoDB server with the first save operation. The same applies to collections.

Full code is available here. If you have any questions please let me know in the comments. The final version of DbClient.connect method looks like this:

public async connect() {
    this.db = await MongoClient.connect("mongodb://localhost:27017/test");
    console.log("Connected to db");
    return this.db;
}

Browsing data stored in MongoDB database

We connected to a MongoDB database and stored the data, so how can we browse the database and the data now? I can recommend you two GUI tools for that Robomongo or MongoDB Compass. On the below screenshot you can see the data that we inserted to our database.

Browsing data stored in MongoDB database with Robomongo

 

shares