,

Tutorial: Creating a CRUD API with Node, Express, and MongoDB

Posted by


In this tutorial, we will learn how to create a CRUD API using Node.js, Express, and MongoDB. CRUD stands for Create, Read, Update, and Delete, which are the basic operations that can be performed on a database.

Prerequisites:
Before we get started, make sure you have Node.js and MongoDB installed on your system. If you don’t have them installed, you can download and install Node.js from the official website (https://nodejs.org/) and MongoDB from the official website (https://www.mongodb.com/).

  1. Create a new Node.js project:
    First, let’s create a new Node.js project. Open your terminal or command prompt and create a new directory for your project. Navigate to the directory and run the following command to initialize a new Node.js project:
npm init -y

This will create a package.json file in your project directory with default settings.

  1. Install dependencies:
    Next, we need to install the required dependencies for our project. We will be using Express and Mongoose to create our CRUD API. Run the following command to install these dependencies:
npm install express mongoose
  1. Set up MongoDB connection:
    Now, let’s set up a connection to MongoDB. In your project directory, create a new file called db.js. In this file, add the following code to connect to MongoDB using Mongoose:
const mongoose = require('mongoose');

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

Replace 'mongodb://localhost:27017/mydatabase' with the connection URL to your MongoDB database.

  1. Create a model:
    Next, let’s create a model for our data. In your project directory, create a new file called model.js. In this file, define a new Mongoose schema for your data:
const mongoose = require('mongoose');

const schema = new mongoose.Schema({
  name: String,
  age: Number
});

module.exports = mongoose.model('Person', schema);

This will create a new Mongoose model named Person with name and age fields.

  1. Create routes:
    Now, let’s create routes for our CRUD operations. In your project directory, create a new file called routes.js. In this file, define routes for creating, reading, updating, and deleting data:
const express = require('express');
const router = express.Router();
const Person = require('./model');

// Create
router.post('/', async (req, res) => {
  try {
    const person = new Person(req.body);
    await person.save();
    res.status(201).send(person);
  } catch (err) {
    res.status(400).send(err);
  }
});

// Read
router.get('/', async (req, res) => {
  try {
    const people = await Person.find();
    res.send(people);
  } catch (err) {
    res.status(500).send(err);
  }
});

// Update
router.put('/:id', async (req, res) => {
  try {
    const person = await Person.findByIdAndUpdate(req.params.id, req.body, { new: true });
    res.send(person);
  } catch (err) {
    res.status(404).send(err);
  }
});

// Delete
router.delete('/:id', async (req, res) => {
  try {
    const person = await Person.findByIdAndDelete(req.params.id);
    res.send(person);
  } catch (err) {
    res.status(404).send(err);
  }
});

module.exports = router;
  1. Set up Express server:
    Finally, let’s set up an Express server to handle our API requests. In your project directory, create a new file called server.js. In this file, add the following code to set up the server:
const express = require('express');
const db = require('./db');
const routes = require('./routes');

const app = express();

app.use(express.json());
app.use('/api/people', routes);

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

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
  1. Run the server:
    To run the server, simply run the following command in your project directory:
node server.js

This will start the Express server on port 3000 (or the port specified in the PORT variable). You can now test your CRUD API using tools like Postman or curl.

That’s it! You have successfully created a CRUD API using Node.js, Express, and MongoDB. Feel free to customize the API according to your needs and add more routes and functionality. Happy coding!

0 0 votes
Article Rating

Leave a Reply

48 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@CodingCleverly
2 hours ago

It's great to have another video uploaded on the best coding channel on YouTube. Make sure to check out more MERN/NextJS project-based videos from my channel as well!
Link: https://www.youtube.com/@CodingCleverly/

@LongTran-nm3ne
2 hours ago

Is it possible to deploy a backend to github? It's so interesting, I will get a try!

@SaravananS-w3m
2 hours ago

Thank you for this useful content🤗

@gabiie-122
2 hours ago

what extension is he using that gives you prefilled code?

@javlon8392
2 hours ago

Can smn pls explain what do these stuff we r downloading and setting up do i would really appreciate

@JenitJosephJose
2 hours ago

Thank you, bro! It was really interesting. It taught me about API functions and CRUD operations. Watching this and coding is a valuable use of time. It is very understandable and explained in simple language.

@WaWa-Zd8
2 hours ago

Love this😍

@WhatAMoron-007
2 hours ago

is he high?

@janitharanasinghe7914
2 hours ago

Great tutorial Thanks a lot ❤

@ssikarim
2 hours ago

Thanks

@MUSTAPHAEL-AZZAOUY
2 hours ago

Thank you so much

@roshankumarkarna2282
2 hours ago

forced to appreciate after seeing your lecture. Simply Awesome. You made me learn crud operations . i was wandering here and there but was not getting the right material.Thanks once again.

@smdas45
2 hours ago

Does this video go over creating a RestFul API

@dev.saadhossain
2 hours ago

very bad approach to teach! time wasting

@msh8769
2 hours ago

so many libraries 🙁
annoying

@ibrahimhossen6549
2 hours ago

awesome tutorial, thank you

@Pywyoyuyp
2 hours ago

Thanks I loved watching this video to revise what I learned. Is this considered front or back end?

@professorpoke
2 hours ago

Is this video beginner friendly ?

@amrsam1985
2 hours ago

thank you very much

@kannuthakur2993
2 hours ago

I am 10 year old and i learn how to make a crud API

48
0
Would love your thoughts, please comment.x
()
x