Back to Blog

MERN Jest Testing (Part 1)

Janvier Muhawenimana

Setup Express App With MongoDB (Part 1)

We are going to build a blog api with node and express, the app will contain the users model and blogs model , the app will be simple and has no authentication.

Requirements

‍

Packages

Now we can start to build the project.

Step 1: Create a project folder


mkdir blog_api 
cd blog_api

Initialize the Project

npm init --y

You will be asked some questions, you can answer them or skip the questions by pressing ENTER, after this step you will have a package.json file into your folder.

Step 2: Install dependencies


npm install express express-validator dotenv cors mongodb mongoose morgan

Also, we need to add the dev dependencies


npm install --save-dev nodemon

Dev dependencies are those packages in the package. json file that you need only for project development purposes.

At the end your package.json will look like this

{
  "name": "blog_api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "express-validator": "^6.14.2",
    "mongodb": "^4.13.0",
    "mongoose": "^6.8.1",
    "morgan": "^1.10.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.20"
  }
}

Step 3: Create the server

Create a server.js file and add the code below


const express = require("express");
var cors = require("cors");
const bodyParser = require("body-parser");
require("dotenv").config(); // Allows us to access variables in .env file

// Initialize the app
const app = express();
const port = process.env.PORT || 8000;

app.use(cors()); // Use cors 

app.use(bodyParser.json({ limit: "25mb" }));

app.get("/", (req, res) => res.send("Express + Testing")); // Simple route

app.listen(port, () => { // Start the server
  console.log(`πŸš€ Server is running at https://localhost:${port}`);
});

This is a simple express server which will return the Express + Testing

Step 4: Modify the package.json

In package.json inside the scripts add the code "start": "nodemon server.js" .

This will refresh your server each time you make changes.


"scripts": {
    "start": "nodemon server.js"
},

Now you can run npm start in your terminal to start your app.

If you visit http://localhost:8000/ in your browser, the app will return Express + Testing

Step 5: Project structure

  • If you are using mac , linux or bash Run the command below in your terminal.

mkdir {controller,enums,models,mongo,router,schemas,service,utils}


  • If you are using windows run this

md controller enums models mongo router schemas service utils


Or create the folders manually

  • controller
  • enums
  • models
  • mongo
  • router
  • schemas
  • service
  • utils

Step 6: Create a database connection

Create a file connection.js inside the mongo folder and add the code below


const mongoose = require("mongoose");
mongoose.set("strictQuery", true);

const MONGO_URL = process.env.MONGO_URL;

class MongoManager {
  constructor() {
		// Check if the MONGO_URL is provided
    if (!MONGO_URL) throw new Error("No connection found");
    this.mongoUrl = MONGO_URL;
  }

  getMongoUrl() {
    return this.mongoUrl;
  }

  connect() {
    try {
      return mongoose.connect(this.getMongoUrl(), {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      });
    } catch (error) {
      throw new Error("Failed to connect");
    }
  }

  disconnect() {
    return this.disconnect();
  }
}

const mongoManager = new MongoManager();

module.exports = mongoManager;

For MongoDB connection we are using a class with

  • constructor: That assign the URL value to this.mongoUrl.
  • getMongoUrl: Return the connection URL.
  • connect: Connect to the database.
  • disconnect: Disconnect to the database.

For the connection we are using mongoose.connect() the connection URL is imported from .env file

Now create the .env file in the main folder and add the code below.


PORT=8000
MONGO_URL="mongodb://localhost:27017/blog_app"

If you are using <mongodb atlas> replace the <MONGO_URL> value with your URL.

Step 7: Connect the app

Import the database connection and connect the app by adding

const mongoManager = require("./mongo/connection"); and mongoManager.connect(); in server.js


const express = require("express");
var cors = require("cors");
const bodyParser = require("body-parser");
require("dotenv").config();

const mongoManager = require("./mongo/connection"); // πŸ‘ˆ import connection
const router = require("./router");

const app = express();
const port = process.env.PORT || 8000;

app.use(cors());

mongoManager.connect();  // πŸ‘ˆ Connect to the database
app.use(bodyParser.json({ limit: "25mb" }));

app.get("/", (req, res) => res.send("Express + Testing"));

app.use(router); //  πŸ‘ˆ App router
app.listen(port, () => {
  console.log(`πŸš€ Server is running at https://localhost:${port}`);
});

module.exports = app;

If you don’t receive the message Failed to connect in your terminal, Β that means your application is connected to the database.

Share on social media:Β