DEV Community

Sunil Kumar Samanta
Sunil Kumar Samanta

Posted on • Updated on

REST API Structure using NodeJS MongoDB (Mongoose)

Alt Text

[UPDATE 2] New modified more robust structure with Generation Tool. Check out here https://dev.to/sunilksamanta/calmapi-a-production-ready-rest-api-generator-using-nodejs-mongodb-pd9

[UPDATE] There are structure improvements and addon features. Please follow the git repo for updated structure.

For each and every project I usually prefer using different architectures. It not just helps me explore new techniques but helps me make the next project better than before by applying the best of them and leave the worst.

Few months ago I found this article interesting. With writing a very minimum line of code you’ll get an API ready. I followed this structure and created my own with some customization and added basic modules and made it REST ready out of the box. The project features —

  1. Controller, Model & Service oriented architecture

  2. Auth with JWT & Db Store

  3. User Module

  4. Post Module (Sample CRUD)

  5. Media Upload

  6. Centralized Http Response

  7. Error Handler

  8. .env support

  9. Multi Environment config setup

  10. Autobind Methods

If you’re too lazy to read further, here is the github repo for full project.

GitHub logo sunilksamanta / node-mongoose-setup

Nodejs MongoDB REST API Sarter

REST API Setup Nodejs MongoDB

example workflow name Build Status Maintainability FOSSA Status PRs Welcome GitHub issues GitHub stars Twitter

Installation

Setup is super easy. Clone the repository -

git clone https://github.com/sunilksamanta/node-mongoose-setup
cd node-mongoose-setup
npm install
Enter fullscreen mode Exit fullscreen mode

Create an .env file at the root of your project with the following.

MONGO_URL=YOUR_MONGO_URL
PORT=5000[YOUR_DESIRED_PORT]
NODE_ENV=YOUR_APP_ENVIRONMENT[production/development]
JWT_SECRET=YOUR_JWT_SECRET_STRING

An example file .env.example is included.

Your project is ready. Now start the project.

npm start
Enter fullscreen mode Exit fullscreen mode

Go to http://localhost:5000. You should see a default welcome page.

Your API base path is http://localhost:5000/api.

First create some accounts to get started with the authentication.

Authentication

JWT authentication is added in this project. User model is defined in models/User.js For Register, Login, Logout use these urls —

    [POST] api/auth/register
    [POST] api/auth/login
    [GET] api/auth/logout

Features

  1. Controller, Model & Service oriented architecture

  2. Auth with JWT & Db Store

  3. Async/Await support

  4. User Module

  5. Post Module (Sample CRUD)

  6. Media Upload

  7. Centralized Http Response

  8. Error Handler

  9. .env support

  10. Multi Environment config setup

  11. Autobind Methods

  12. Built in Pagination

Directory Structure of the Project

├─

Lets dig into the Matrix..

What we’re using?

  1. NodeJS

  2. MongoDB (Mongoose ODM)

Directory Structure of the Project

       ├─ .env
       ├─ .gitignore
       ├─ config
       │  ├─ config.js
       │  ├─ database.js
       │  ├─ routes.js
       │  └─ server.js
       ├─ index.js
       ├─ package.json
       └─ src
          ├─ controllers
          │  ├─ AuthController.js
          │  ├─ Controller.js
          │  ├─ MediaController.js
          │  └─ PostController.js
          ├─ helpers
          │  ├─ HttpError.js
          │  ├─ HttpResponse.js
          │  └─ Utility.js
          ├─ models
          │  ├─ Auth.js
          │  ├─ Media.js
          │  ├─ Post.js
          │  └─ User.js
          ├─ routes
          │  ├─ auth.js
          │  ├─ index.js
          │  ├─ media.js
          │  └─ post.js
          └─ services
             ├─ AuthService.js
             ├─ MediaService.js
             ├─ PostService.js
             ├─ Service.js
             └─ UserService.js
Enter fullscreen mode Exit fullscreen mode

Lets talk about the structure

If you’ve already read the article where I found the struture then you’ve already understood what the structure does. If not please follow this link for better understanding of the basics of this architecture.

We have 2 base classes — One for Controller and another for Service.

  1. Controller.js

This base controller have the basic CRUD operations. To create a new controller just extend this base Controller class.

  1. Service.js

This is the base Service class which includes the database operations. If you want to change the default behaviour of the services you can update this file.

How to Create new CRUD Module?

If you want to create a new Module say Post. Then you’ll have to create 4 basic files. One Controller, one Service, one Model and one route file. And add the new route in routes/index.js with desired url.
There is a “Post” CRUD module included in this project for example.

    controllers/PostController.js
    models/Post.js
    services/PostService.js
    routes/post.js
Enter fullscreen mode Exit fullscreen mode

Overriding Base class method

As an example if you see in the media Controller — the default delete method is overriden by its own class method as we have to delete the file from the file system also. So the overriden method is like bellow —

async delete(req, res, next) {
  const { id } = req.params;
  try {
      const response = await this.service.delete(id);
      // File Unlinking..
      if (response.data.path) {
          console.log("unlink item", response.data.path);
          fs.unlink(response.data.path, function (err) {
              if (err) {
                  console.log("error deleting file");
                  throw err;
              }
              console.log("File deleted!");
          });
      }
      return res.status(response.statusCode).json(response);
  }
  catch (e) {
      next(e);
  }
}
Enter fullscreen mode Exit fullscreen mode

Authentication

JWT authentication is added in this project. User model is defined in models/User.js.
For Register, Login, Logout use these urls —

    [POST] api/auth/register
    [POST] api/auth/login
    [GET] api/auth/logout
Enter fullscreen mode Exit fullscreen mode

Thats all for now.. If you need any help, I’ll love to do so.
Here is once again the git repo..

GitHub logo sunilksamanta / node-mongoose-setup

Nodejs MongoDB REST API Sarter

REST API Setup Nodejs MongoDB

example workflow name Build Status Maintainability FOSSA Status PRs Welcome GitHub issues GitHub stars Twitter

Installation

Setup is super easy. Clone the repository -

git clone https://github.com/sunilksamanta/node-mongoose-setup
cd node-mongoose-setup
npm install
Enter fullscreen mode Exit fullscreen mode

Create an .env file at the root of your project with the following.

MONGO_URL=YOUR_MONGO_URL
PORT=5000[YOUR_DESIRED_PORT]
NODE_ENV=YOUR_APP_ENVIRONMENT[production/development]
JWT_SECRET=YOUR_JWT_SECRET_STRING

An example file .env.example is included.

Your project is ready. Now start the project.

npm start
Enter fullscreen mode Exit fullscreen mode

Go to http://localhost:5000. You should see a default welcome page.

Your API base path is http://localhost:5000/api.

First create some accounts to get started with the authentication.

Authentication

JWT authentication is added in this project. User model is defined in models/User.js For Register, Login, Logout use these urls —

    [POST] api/auth/register
    [POST] api/auth/login
    [GET] api/auth/logout

Features

  1. Controller, Model & Service oriented architecture

  2. Auth with JWT & Db Store

  3. Async/Await support

  4. User Module

  5. Post Module (Sample CRUD)

  6. Media Upload

  7. Centralized Http Response

  8. Error Handler

  9. .env support

  10. Multi Environment config setup

  11. Autobind Methods

  12. Built in Pagination

Directory Structure of the Project

├─

Want to contribute?

If you have any suggestion, feedback or you want to make this project more powerful — feel free to report issues or request a feature or suggest some changes. Fork and PR.

Happy Coding!

Originally published in medium -> REST API Structure using NodeJS MongoDB (Mongoose)

Top comments (2)

Collapse
 
gmcamposano profile image
gmcamposano

Thank you very much!

Collapse
 
miquelvald profile image
Miguel Valdez

Such a bad post lol, dislike.