,

Creating a CRUD RESTful API with Node, Express, and MongoDB

Posted by


CRUD REST API using Node | Express | MongoDB

In today’s digital world, web applications are everywhere. From social media platforms to e-commerce websites, we rely on web applications for various tasks. Behind the scenes, these applications use APIs to communicate with servers and databases. One such API is the CRUD (Create, Read, Update, Delete) REST API, which allows us to perform basic operations on data stored in a database.

In this article, we will explore how to build a CRUD REST API using Node.js, Express, and MongoDB. Node.js is a runtime environment that allows us to run JavaScript on the server-side. Express is a popular web framework for Node.js that makes it easy to build web applications. MongoDB is a NoSQL database that provides a flexible and scalable solution for storing and retrieving data.

Setting up the Project

Before diving into the code, we need to set up our project. Assuming you have Node.js and MongoDB installed, follow these steps:

  1. Create a new directory for your project and navigate to it in the terminal.
  2. Run the command npm init to create a package.json file for your project.
  3. Install the required packages using the command npm install express mongoose body-parser.

Building the API

Now that we have our project set up, let’s start building the API. Create a new file called app.js and add the following code:


const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Database Connection
mongoose.connect('mongodb://localhost/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => {
  console.log('Connected to MongoDB');
}).catch((error) => {
  console.log('Error connecting to MongoDB: ', error);
});

// Define a Schema
const ProductSchema = new mongoose.Schema({
  name: String,
  price: Number
});

// Define a Model
const Product = mongoose.model('Product', ProductSchema);

// Routes
app.post('/api/products', (req, res) => {
  const { name, price } = req.body;

  const product = new Product({ name, price });

  product.save((error, result) => {
    if (error) {
      res.status(500).json({ error });
    } else {
      res.status(201).json({ message: 'Product created successfully', result });
    }
  });
});

app.get('/api/products', (req, res) => {
  Product.find((error, products) => {
    if (error) {
      res.status(500).json({ error });
    } else {
      res.status(200).json({ products });
    }
  });
});

app.put('/api/products/:id', (req, res) => {
  const { id } = req.params;
  const { name, price } = req.body;

  Product.findByIdAndUpdate(id, { name, price }, { new: true }, (error, result) => {
    if (error) {
      res.status(500).json({ error });
    } else {
      res.status(200).json({ message: 'Product updated successfully', result });
    }
  });
});

app.delete('/api/products/:id', (req, res) => {
  const { id } = req.params;

  Product.findByIdAndDelete(id, (error, result) => {
    if (error) {
      res.status(500).json({ error });
    } else {
      res.status(200).json({ message: 'Product deleted successfully', result });
    }
  });
});

// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

In the above code, we have imported the required packages and set up the Express app. We have also established a connection with the MongoDB database using Mongoose. Next, we defined a schema for our product and created a model using the schema.

We then defined the routes for our API. Using the HTTP methods, we created routes for creating, reading, updating, and deleting products. Each route performs the necessary operations on the database and sends an appropriate response back to the client.

Finally, we started the server and listened on port 3000. Now, we are ready to test our API using a tool like Postman.

Conclusion

In this article, we learned how to build a CRUD REST API using Node, Express, and MongoDB. We set up our project, established a connection with the MongoDB database, defined the schema and model for our data, and created routes to perform CRUD operations on the data. This is just the beginning, and there is a lot more you can do with Node, Express, and MongoDB to build powerful web applications.

Remember to handle errors, implement authentication, and add validation as needed to make your REST API more secure and robust. Happy coding!

0 0 votes
Article Rating
20 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Technowind Thunder
7 months ago

Hi sir,

Send code for:
Update & Delete

From mongoDB.

Please sir..

Krishna
7 months ago

Your Content is really good, but i felt using the word alien always becomes confusing to understand, needs more time to know exatctly for what you are representing the aliens for in a particular context, because you are using it everywhere.

CARIFIED
7 months ago

my post request is giving error at 43:24

please help me

Being Human
7 months ago

I heard books as boo*s and got shocked 26:26

Bala Krishnan
7 months ago

This video I've have been searching for all day..

Varahasamy Ramadesikan
7 months ago

This content presented in effective way and teach essential parts effectively. Post videos to improve the novice knowledge

Varahasamy Ramadesikan
7 months ago

In the postman whenever we try to post collections to mongo database change text to json in the field. There are text,xml,javascript so many options are there , you change it to json before posting other try catch shows an error

MUKUTMANI DAS
7 months ago

i'm getting error – ValidationError while using post request in postman its saying Error ValidationError: name: Path `name` is required., tech: Path `tech` is required. how to resolve it

Maninder Singh
7 months ago

nice, well explained

Poonam Babar
7 months ago

Thank you for this Tutorial🙏

Aishwarya
7 months ago

Any one of you facing issues with post request in postman, you might not have selected the format "JSON" after selecting the "raw" radio button.. So set the "Text" dropdown to "JSON" format

MasterWayne9790
7 months ago

Video starts at 8:46

Nitin choudhary
7 months ago

We are belong to virtual world so we are not aliens we are bots😂

G T
G T
7 months ago

❤🧡thank u🙂

Proofread
7 months ago

Very helpful! Thank you!

Ali Akbar
7 months ago

jio

Naveen Chander
7 months ago

really nice

ABU TAHER
7 months ago

is it possible to pupulate between different createConnection models?

ABU TAHER
7 months ago

is it possible mongoose populate between diffrent mongoose.createConnection?

Roku
7 months ago

13:48…I am having troubles here…I am following the syntax but still I am having an error. What to do?