Select section

Voting API using Node.js and MongoDB

"This is a Voting API built using Node.js, Express, and MongoDB. It allows users to create polls, vote, and view results."

by Karan Kumar Gautam

02/03/2025

πŸ‘‹πŸŒ

Welcome to this tutorial on building a Voting API using Node.js, Express, and MongoDB. This project demonstrates how to build a RESTful backend for managing voting polls β€” including creation, voting, and result viewing β€” in a clean and modular way.

Introduction to the Voting API

The Voting API is a backend project that lets users:

This project is ideal for learning how REST APIs work, managing a MongoDB database using Mongoose, and structuring a scalable Node.js backend.


Project Setup

To run this API on your machine, follow these steps:

1. Clone the Repository

git clone https://github.com/gautamkaran/Voting-api.git
cd Voting-api

2. Install Dependencies

npm install

3. Create .env File

Add your MongoDB URI and port in a new .env file:

PORT=5000
MONGO_URI=mongodb://localhost:27017/voting-api

4. Start the Server

npm start

The server will start on http://localhost:5000


API Features

βž• Create a New Poll

Endpoint: POST /api/vote/create

Request Body:

{
  "question": "What is your favorite frontend framework?",
  "options": ["React", "Vue", "Angular", "Svelte"]
}

πŸ—³οΈ Vote on a Poll

Endpoint: PUT /api/vote/:id

Request Body:

{
  "option": "React"
}

πŸ“ƒ View All Polls

Endpoint: GET /api/vote

Returns a list of all polls with their questions, options, and vote counts.


Tech Stack


Folder Structure

Voting-api/
β”‚
β”œβ”€β”€ config/              # Database connection
β”‚   └── db.js
β”œβ”€β”€ models/              # Mongoose models
β”‚   └── Vote.js
β”œβ”€β”€ routes/              # API routes
β”‚   └── voteRoutes.js
β”œβ”€β”€ server.js            # Entry point
β”œβ”€β”€ .env                 # Environment variables
β”œβ”€β”€ package.json         # Dependencies
└── README.md

Sample Data Flow

1. User sends a POST request to /api/vote/create

2. Another user sends a PUT request to /api/vote/:id

3. A GET request to /api/vote returns the list of all polls with results


Ideal Use Cases


Author

Karan Kumar Gautam
πŸ”— GitHub | 🌐 Portfolio


License

MIT – Use it freely in your projects


Conclusion

This Voting API project is a great way to get hands-on experience with REST APIs, MongoDB, and Node.js. It’s clean, easy to extend, and ready to be used in real applications.

Happy coding!