Skip to content
Writing
100% Human-Written

TypeScript Integration with MongoDB Guide | MongoDB

August 18, 20219 min read
Technical
This is my original tutorial, republished on this website. The examples are preserved. Tool versions and interfaces may have changed.
Microsoft developed TypeScript as a superset of JavaScript that has a single open-source compiler. It is a strict syntactical language that provides optional static typing, classes and interfaces. In addition to many other languages, MongoDB also supports TypeScript through TypeScript drivers. Learn more about TypeScript integration with MongoDB now. This tutorial assumes that you have some familiarity with Node.js and MongoDB Atlas.
In Javascript, you can reference variables that don't exist or work with objects of unknown shape. If your code has errors, you won't catch it until runtime. To avoid this problem, TypeScript was introduced. Since TypeScript is a compiled language, it validates your JavaScript ahead of time with static type checking, reducing the time taken to resolve errors. Furthermore, TypeScript also supports interfaces and classes letting you create more robust projects.
This project will use npm throughout the tutorial. If you have not already, install the Node Package Manager (npm). If you want to work with yarn instead of npm, run the following command to install yarn in your system.
npm install --global yarn
Replace npm install in the examples below with yarn add wherever required.
We will start by creating a typeScriptProject folder and initialize a project inside it. To set up the project, run the following command in your terminal.
#Making the folder
mkdir typeScriptProject

#entering the folder
cd typeScriptProject

#creating the required folder
mkdir src
#Initialising with package(dot)json file
npm init -y

#If you prefer to use yarn
#yarn init -y
After initializing the project, run the following command to add the dependencies required to build the project.
# dependencies
npm install express mongodb cors dotenv
The command above uses a couple of keywords.
  • mongodb command installs MongoDB database driver that allows your Node.js applications to connect to the database and work with data.
  • express installs the web framework for Node.js (it will make our life easier),
  • cors installs a node. js package that allows cross origin resource sharing.
  • dotenv installs the module that loads environment variables from a .env file into the process.env file. This lets you separate configuration files from the code.
We can check out installed dependencies using the package.json file. It should list the packages along with their versions. Continue running the following commands to install TypeScript and nodemon modules.
# devDependencies
npm install -D nodemon TypeScript ts-node @types/express @types/mongodb @types/node
This command uses the following keywords:
  • nodemon command restarts the Node application whenever changes in the files in the directory are detected.
  • TypeScript command adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS.
  • ts-node command transforms TypeScript into JavaScript, enabling you to directly execute TypeScript on Node.js without precompiling.
  • @types refers to the package containing the definition for the specific types.
To configure the TypeScript compiler, create a tsconfig.json file in the root directory. This file informs the compiler of the locations of the TypeScript files. By default, TypeScript will compile the code to JavaScript ES3. Copy and paste the following code in tsconfig.json file to configure the TypeScript to use JavaScript ES6 import/export syntax.
{
  "compilerOptions": {
    /* Basic Options */
    "target": "es6",
    "watch": true,
    "module": "commonjs",
    "outDir": "./dist",
    /* Strict Type-Checking Options */
    "strict": true,      
    "esModuleInterop": true,
    /* Source Map Options */
    "sourceRoot": "./src",
    "inlineSourceMap": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", ".vscode"]
}
In the above json file,
  • target field specifies the JavaScript version of the destination code. By setting it to ES6, we ensure the destination code will be in JavaScript version ES6.
  • watch field, when set to true, recompiles the code every time we save it.
  • sourceRoot field specifies the folder where we will store all the TypeScript files.
  • outDir field indicates the folder where all the JavaScript files will be exported.
  • include field specifies the folders we want to include during compilation.
  • exclude field specifies the folders we do not want to include during compilation.
Once done, add the following code to the package.json file. This file indicates the scripts we want to run during the compilation.
  "scripts": {
    "start": "node dist/index.js",
    "dev": "nodemon src/index.ts",
    "build": "tsc -p ."
  },
Inside the src folder, create index.ts file and paste the following code in it.
import express, { Request, Response } from 'express';

const app = express();

app.get('/', (req:Request, res:Response) =>{
    res.send("Hello");
});

app.listen(5000, ()=>console.log(`Server is running on port 5000`));
Run the code using npm run dev on your terminal. You should get the “Server is running on port 5000” message in your terminal. If you go to http://localhost:5000/ you will also get a Hello message.
Time to connect our server to the database. We will use MongoDB Atlas as the database. MongoDB Atlas is a cloud-based database service that provides robust data security and reliability. Don’t have a MongoDB Atlas database? You can create a free account for MongoDB Atlas here.
MongoDB Atlas provides a free tier cluster that never expires and lets you access a subset of Atlas features and functionality.
To create a new database cluster:
  1. Sign in to your MongoDB Atlas account then, click on Build a cluster.
  2. Choose the region closest to you and click on Create Cluster.
  3. Go to Network access on the left-hand side and add your IP address to the Whitelist.
  4. On the Database access, just above network access, add a database user. For this tutorial, we will add a user mern with the password mongodb.
  5. Go to Clusters and click on Connect.
  6. Choose Connect your application as your connection method.
MongoDB Atlas connection method selection
  1. Copy the connection string. We will use it in our application to connect to MongoDB.
MongoDB Atlas application connection string Now if you have the connection string, let’s go back to the root directory (directory that contains src folder) and create a .env file. Paste the connection string to the ATLAS_URI variable. Once done, your file should look similar to the one below.
ATLAS_URI=mongodb+srv://<username>:<password>@sandbox.jadwj.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
PORT=5000
Replace the <username> and the <password> with your database username and password. In the index.ts file, add the following code to connect to our database.
import express, { Request, Response } from 'express';
import dotenv from "dotenv";
const MongoClient = require('mongodb').MongoClient
const app = express();
dotenv.config();

const uri = process.env.ATLAS_URI

MongoClient.connect(uri,{ useNewUrlParser: true, useUnifiedTopology: true }, (err:any, client:any) => {
    if (err) return console.error(err)
    console.log('Connected to Database')
  })

app.get('/', (req:Request, res:Response) =>{
    res.send("Hello");
});

app.listen(5000, ()=>console.log(`Server is running on port 5000`));
If you successfully connect to MongoDB Atlas, you will get the message “Connected to Database” in your terminal.
To add models, create a routes folder and a documentRoutes.ts file in it. In the file, we will add the codes to define the models to get, post, update, and delete data from our database. Use the following code in documentRoutes.ts file.
import express, { Request, Response, Router } from 'express';
const documentRoutes = express.Router();
const mongodb = require('mongodb');
const uri = process.env.ATLAS_URI

// Using this we will connect to the database
async function dataWithDatabase() {
  const client = await mongodb.MongoClient.connect(
    uri,
    {
      useNewUrlParser: true,
      useUnifiedTopology: true 
    }
  );
// Here, test is the database and mongo is the collection
  return client.db('test').collection('mongo');
}


// This section will help you get a list of all the documents.
documentRoutes.route("/document").get( async (req:Request, res:Response) => {
  const documents = await dataWithDatabase();
  res.send(await documents.find({}).toArray());
});

// This section will help you create a new document.
documentRoutes.route("/document/add").post(async (req:Request, res:Response) => {
  const documents = await dataWithDatabase();
  await documents.insertOne({
    text: req.body.text,
    createdAt: new Date()
  });
  res.status(201).send();
  console.log("Record added")
});

// This section will help you update a document by id.
documentRoutes.route("/update/:id").post(async (req:Request, res:Response) => {
  const documents = await dataWithDatabase();
  let document ={text: req.body.text, createdAt: new Date()}
  await documents.updateOne({id: req.body.id}, {$set:document}, {upsert:true} );
  res.status(200).send({});

});

// This section will help you delete a document
documentRoutes.route("/:id").delete(async(req:Request, res:Response) => {
  const documents = await dataWithDatabase();
  await documents.deleteOne({ _id: new mongodb.ObjectID(req.params.id) });
  res.status(200).send({});
});

module.exports = documentRoutes;
Using the above code, we have created the following routes.
  • /document - to show all the documents
  • /document/add - to add documents
  • /update/:id - to update document with specific id
  • /:id - to delete document with specific id
Using the require() method, load the documentRoutes file from index.ts file. The final version of the index.ts file should look like the following.
import express from 'express';
import dotenv from "dotenv";

const app = express();
dotenv.config();
app.use(express.json())

var mainRoutes = require('./routes/documentRoutes') 
app.use(mainRoutes);

app.listen(5000, ()=>console.log(`Server is running on port 5000`));
To test the route, ensure the terminal is running. If you are not sure that the terminal is running, execute the command npm run dev in your terminal. To test the routes, we have used Postman. If you have access to Postman, add some data to the body of the JSON file. Select the POST option and on the URL bar, enter the URL - localhost:5000/document/add. Click on Body and choose the raw option. Then, choose JSON from the drop-down and click Send.
Postman request to add a document
If successful, you will get the “document added” message on your console. To check if the document was inserted, go to your MongoDB Atlas database. You can find the inserted document under the specified Collections of your database. Inserted document in MongoDB Atlas Continue testing the update and delete route using Postman and JSON data following the steps specified above. An update URL would look like the following. http://localhost:5000/update/<id> While a delete URL would look like the following. http://localhost:5000/<id> For each of these routes, you will need the <id> of the documents. To view all the documents, use the following URL. http://localhost:5000/document
Most of the applications used in the real world are built around CRUD operations. For a ToDo application, creating an entry requires you to insert data into the database. To read all the entries in the program, you will be pulling a list of documents from the database. Similarly, removing an entry is synonymous to deleting data from a database and changing an entry requires you to update the database. Using these basic principles, you can create various other programs such as shopping lists, expense trackers or project management applications.
What we have made here is an example of a simple CRUD application using RESTful API, Nodejs, Express, MongoDB, and TypeScript. You can find the entire code for this application in GitHub. Using these concepts of interacting with a database such as MongoDB, you will be able to build bigger and robust projects in the future.