ExpressJS CRUD Operations
Description
In this tutorial, we will learn how to perform CRUD (Create, Read, Update, Delete) operations in a Node.js web application using Express.js framework.
Syntax
Here is the basic syntax for CRUD operations in Express.js:
Create Data
app.post('/create', function(req, res) {
// Code to create data
});
Read Data
app.get('/read', function(req, res) {
// Code to read data
});
Update Data
app.put('/update/:id', function(req, res) {
// Code to update data
});
Delete Data
app.delete('/delete/:id', function(req, res) {
// Code to delete data
});
Example
Let's consider a basic example of how to perform CRUD operations using Express.js with MongoDB as the database.
const express = require('express');
const bodyParser = require('body-parser');
const mongodb = require('mongodb');
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const MongoClient = mongodb.MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'testdb';
let db;
MongoClient.connect(url, function(err, client) {
if (err) throw err;
db = client.db(dbName);
app.listen(port, function() {
console.log('Server is listening on port', port);
});
});
// Create Data
app.post('/create', function(req, res) {
let data = {
name: req.body.name,
age: req.body.age,
email: req.body.email
};
db.collection('users').insertOne(data, function(err, result) {
if (err) res.send(err);
res.send('Data added successfully');
});
});
// Read Data
app.get('/read', function(req, res) {
db.collection('users').find({}).toArray(function(err, result) {
if (err) res.send(err);
res.send(result);
});
});
// Update Data
app.put('/update/:id', function(req, res) {
let id = req.params.id;
db.collection('users').updateOne(
{ _id: mongodb.ObjectId(id) },
{ $set: { age: req.body.age } },
function(err, result) {
if (err) res.send(err);
res.send('Data updated successfully');
}
);
});
// Delete Data
app.delete('/delete/:id', function(req, res) {
let id = req.params.id;
db.collection('users').deleteOne({ _id: mongodb.ObjectId(id) }, function(
err,
result
) {
if (err) res.send(err);
res.send('Data deleted successfully');
});
});
Output
When you run this code, it will create a web server which listens on port 3000. You can use Postman or any other REST client to test this API.
Here are the outputs of each operation:
Create Data
If you send a POST request to http://localhost:3000/create
with the data in JSON format, it will insert that data in the database and return a response with a message "Data added successfully".
Read Data
If you send a GET request to http://localhost:3000/read
, it will read all the data from the database and return a response with the data.
Update Data
If you send a PUT request to http://localhost:3000/update/:id
with the ID of the document you want to update and the new age, it will update that document in the database and return a response with a message "Data updated successfully".
Delete Data
If you send a DELETE request to http://localhost:3000/delete/:id
with the ID of the document you want to delete, it will delete that document from the database and return a response with a message "Data deleted successfully".
Explanation
In this example, we have used Express.js as the web framework and MongoDB as the database. We have created a connection to the database using the MongoDB driver for Node.js. We have defined 4 endpoints for the CRUD operations and implemented the corresponding logic for each operation.
Create Data
To create data, we have defined an endpoint /create
which accepts a POST request with the data in JSON format. We have extracted the data from the request body and inserted it into the MongoDB collection using the insertOne()
function.
Read Data
To read data, we have defined an endpoint /read
which accepts a GET request. We have used the find()
function with an empty filter to retrieve all the documents from the MongoDB collection.
Update Data
To update data, we have defined an endpoint /update/:id
which accepts a PUT request with the ID of the document to be updated and the new age value. We have used the updateOne()
function with the filter on the ID and the set
operator to update the age field of that document.
Delete Data
To delete data, we have defined an endpoint /delete/:id
which accepts a DELETE request with the ID of the document to be deleted. We have used the deleteOne()
function with the filter on the ID to delete that document from the MongoDB collection.
Use
CRUD operations are the most fundamental operations in any web application. Any time you want to create, read, update, or delete data from a database in your Node.js web application, you can perform these operations using Express.js with any database of your choice.
Important Points
- You can use any database of your choice with Express.js to perform CRUD operations.
- Always use prepared statements or parameterized queries to avoid SQL injection attacks.
- Always validate user input and sanitize data to prevent XSS (Cross-Site Scripting) attacks.
Summary
In this tutorial, we have learned how to use Express.js framework to perform create, read, update, and delete operations on a MongoDB database. We have covered the syntax, example, output, explanation, use cases, and important points of Express.js CRUD operations. You can use this knowledge to create your own web applications using Node.js and Express.js.