API Server Setup with Express.js, TypeScript, and MongoDB

Part 3: Adding MongoDB to our API

Ward Price
JavaScript in Plain English

--

We will continue from where we left off in this tutorial series by adding MongoDB to our API. If you are just starting now feel free to clone all the code from the previous tutorial here.

First we need to download the MongoDB community server. Make sure to pick the right download for your operating system and then follow the instructions to install and get it running on your system on your system. MongoDB community server is completely free for anyone to use!

Now back to the project. In your /src folder create a file named connect.ts. It’s here we will write the configuration for express to connect to the database. In order to connect to the database we will need to use an Object-data modeling (ODM) tool. Using an ODM will allow provide some structure and built in business logic which will make our lives a lot easier, less writing more doing! Probably the most popular ODM for MongoDB is Mongoose so let’s install it and because we are using typescript, its types.

$ npm i mongoose
$ npm i -D @types/mongoose

Open the connect.ts file and import mongoose with the line

import mongoose from 'mongoose';

Next we need to create a function that will take the database address and what to do if the connection is successful or throws an error.

export default ({ db }) => {
const connect = () => {
mongoose
.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
.then(() => {
return console.info('Successfully connected to Database');
})
.catch((error) => {
console.error('Error connecting to database: ", error);
return process.exit(1);
});
};
connect()
mongoose.connection.on('disconnected', connect);
};

Using the database string we try to connect to the database. If we are successful we will print to the database Successfully connected to Database. If not, the error message Error connecting to database will be logged along with the error message from the system and the connection attempt will be exited.

However, because we are using type script you are probably getting a red squiggly line underneath db. This is because typescript has no idea what type db should be. We know it’s only going to be a string so lets make a new type in connect.ts to tell typescript “Hey, this variable db is only going to be a string”

type TDBInput = {
db: string;
};

Now all we need to do tell typescript to use that type. The way to do that is to add : TDBInput after { db } in the function parameter. Your full connect.ts should look like this.

Now to add our MongoDB connection to our server open /src/index.ts. Let’s first import the connect.ts file we just made by adding the following line to our import statements.

import connect from './connect';

At the very bottom declare the constant db and set it equal to your local MongoDB instance that should be running. The default is mongodb://localhost:27017. After the address you can add the name of the collection you want to create, if that collection does not exist MongoDB will automatically create it. Since we are making a movie lookup app we will name ours movies

const db = 'mongodb://localhost:27017/movies';

Only thing left to do is to use the connect function we imported and set it to our db constant.

connect({ db });

Your /src/index.ts file should now look like this.

If you start the server by using the $ npm start command in terminal it’ll take a minute but you should recieve the message that you successfully connected to the database!

Full code to clone

Next time we create some data models and start getting into posting data to MongoDB

Happy coding

Tutorials in Series

Part 1: “Hello World!”

Part 2: Setting Up The Router

Part 3: Connecting to MongoDB

--

--