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/).
- 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.
- 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
- Set up MongoDB connection:
Now, let’s set up a connection to MongoDB. In your project directory, create a new file calleddb.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.
- Create a model:
Next, let’s create a model for our data. In your project directory, create a new file calledmodel.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.
- Create routes:
Now, let’s create routes for our CRUD operations. In your project directory, create a new file calledroutes.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;
- 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 calledserver.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}`);
});
- 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!
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/
Is it possible to deploy a backend to github? It's so interesting, I will get a try!
Thank you for this useful content🤗
what extension is he using that gives you prefilled code?
Can smn pls explain what do these stuff we r downloading and setting up do i would really appreciate
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.
Love this😍
is he high?
Great tutorial Thanks a lot ❤
Thanks
Thank you so much
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.
Does this video go over creating a RestFul API
very bad approach to teach! time wasting
so many libraries 🙁
annoying
awesome tutorial, thank you
Thanks I loved watching this video to revise what I learned. Is this considered front or back end?
Is this video beginner friendly ?
thank you very much
I am 10 year old and i learn how to make a crud API