,

A Real-World Project: Creating a Node.js REST API for a Social Media Backend using Node Express MongoDB

Posted by



HTML Tags to Use:


Build A Social Media Backend REST API With Node.JS | Node Express MongoDB Real-World Project

Build A Social Media Backend REST API With Node.JS

Node Express MongoDB Real-World Project

In this tutorial, we are going to build a social media backend REST API using Node.JS, Express, and MongoDB. By the end of this project, you will have a fully functional API that can handle user authentication, post creation, comment system, and more.

Prerequisites

  • Basic knowledge of JavaScript and Node.JS.
  • Understanding of REST APIs and HTTP methods (GET, POST, PUT, DELETE).
  • Familiarity with Express framework for Node.JS.
  • Installation of MongoDB database.

Setting Up the Project

First, let’s create a new directory for our project and navigate into it:


mkdir social-media-api
cd social-media-api

Next, initialize a new Node.JS project:


npm init -y

Now, let’s install the necessary dependencies:


npm install express mongoose dotenv

Creating the Server

Create a new file called server.js and add the following code:


const express = require('express');
const app = express();

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

This code imports the required dependencies, creates an instance of the Express app, and starts the server on the specified port.

Connecting to MongoDB

In order to connect to the MongoDB database, create a new file called db.js and add the following code:


const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/social-media', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB successfully');
}).catch((err) => {
console.error('Error connecting to MongoDB', err);
});

Make sure to replace the connection URL with your own MongoDB connection string.

Defining the Routes

Create a new directory called routes and inside it, create a file called users.js. Add the following code:


const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
// Retrieve all users from the database
res.send('Get all users');
});

router.get('/:id', (req, res) => {
// Retrieve a single user by ID from the database
res.send(`Get user with ID ${req.params.id}`);
});

router.post('/', (req, res) => {
// Create a new user in the database
res.send('Create a new user');
});

module.exports = router;

This code defines the routes for retrieving all users, retrieving a single user by ID, and creating a new user. These routes are then exported for use in the main server.js file.

Using the Routes

In the server.js file, add the following code to use the routes:


const userRoutes = require('./routes/users');

app.use('/users', userRoutes);

This code imports the user routes from the users.js file and registers them under the /users endpoint.

Conclusion

Congratulations! You have successfully built a social media backend REST API using Node.JS, Express, and MongoDB. This project is a great starting point for developing your own real-world applications and can be extended to include additional features.

0 0 votes
Article Rating
20 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Indian Coders
1 year ago

Build an AI Chatbot (ChatGPT Clone) With MERN Stack

https://youtu.be/PX_YOfEdhRg

Anamika Sarkar
1 year ago

Please share source code

Samuel Edem Jerry-Kanfra
1 year ago

Your style of teaching fits my understanding … hope you take up more project with flutter, nodejs, mongodb to help us learn more

Dharmendra Kumar
1 year ago

bhai mat dekhna jitna tum dekhoge nahi usse jayada ye ad ata hai bahot jyada

surajit Halder
1 year ago

Great tutorial ,very nice video ,got clear lot of doubts,thank you ❤

Alison oZ
1 year ago

Hello! Why did you changed the start script at 5:42 ? Why is it important?

Joseph Kay
1 year ago

Why is the app.js appearing with the react symbol, yet you had not installed react

Micheal Adisa
1 year ago

Great tutorial here, well done and thanks.

What VS Code extension do you use that suggests the autocomplete keywords for mongo?

Md Fahad
1 year ago

got an error in terminal =
throw new Error('data and salt arguments required');
Error: data and salt arguments required

Naan Ahmed
1 year ago

Thank you very much!

MØVÍÉS WÖRLD { Explanation }
1 year ago

i got an error on data and salt arguments required

Aishwarya N R
1 year ago

stuck with cast error , can someone help

Mohammed Khan
1 year ago

node: bad option: –es-module-specifer-resolution=node why is this note error comming

sahil jaggarwal
1 year ago

52:49 pe blog add nahi ho raha hai aur terminal me koi error show nahi kar rha hai

Sumit Raj
1 year ago

sir what is mongoose.startSession and session.startTransaction() ? i don't know what they do

Indian Coders
1 year ago

🤘Build A FULL Stack BLOG App With MERN Stack and GraphQL API
🚀https://youtu.be/rBQlFetNb84

Sallyz Vibe
1 year ago

ONE OF THE BEST And easy tutorial for beginners .

Pushpa Kumari
1 year ago

I having issues when connected to mongoose , can anyone help me??

HARSH MISHRA
1 year ago

please make one more video by using schema and relationship in mongodb. So that we learn relation between collection

Vineet Kumar
1 year ago

Everything Is crystal Clear. Thanks a lot.