Anon Sike

Anon Sike

1593224949

How to Connect Express REST API with MongoDB and CRUD operations using TypeScript

A REST API needs a database to save our data, just like any application. A database can be a text file, SQL database (like MySQL or Post SQL) or NoSQL database (like MongoDB or Redis). In this article, you will learn how to connect your REST API with MongoDB. Please refer to my previous article to install MongoDB to your machine. You can find a complete guide about how to build your REST API up to here in the following articles.

  1. Setup REST API with Node.js Express
  2. Project structure and building routes of REST API with Node.js Express

The final aim of building an API is to host on a server and use it for mobile or web applications. So we build it in one environment and host in another environment. So it is a good practice if you manage those environments in a separate file. Then you can manage different port numbers, database names for each environment easily. Inside the lib folder create a file named environment.ts.

enum Environments {
    local_environment = 'local',
    dev_environment = 'dev',
    prod_environment = 'prod',
    qa_environment = 'qa'
}

class Environment {
    private environment: String;

    constructor(environment: String) {
        this.environment = environment;
    }

    getPort(): Number {
        if (this.environment === Environments.prod_environment) {
            return 8081;
        } else if (this.environment === Environments.dev_environment) {
            return 8082;
        } else if (this.environment === Environments.qa_environment) {
            return 8083;
        } else {
            return 3000;
        }
    }

    getDBName(): String {
        if (this.environment === Environments.prod_environment) {
            return 'db_test_project_prod';
        } else if (this.environment === Environments.dev_environment) {
            return 'db_test_project_dev';
        } else if (this.environment === Environments.qa_environment) {
            return 'db_test_project_qa';
        } else {
            return 'db_test_project_local';
        }
    }
}

export default new Environment(Environments.local_environment);

In a previous article, we initialized a PORT number at the server.ts file. Now we can replace it with the getPort() method in environment class.

import app from "./config/app";
import env from './environment'

const PORT = env.getPort();

app.listen(PORT, () => {
   console.log('Express server listening on port ' + PORT);
});

#express #mongodb #nodejs #typescript #rest-api

How to Connect Express REST API with MongoDB and CRUD operations using TypeScript