First, We learn what the CRUD operation is, then we will understand step by step with a backend code (express.js).
CRUD stands for Create, Read, Update, and Delete. These are the four basic things you can do with data in a database:
Create:
Add new data to the database.
Example: Imagine you're adding a new coffee to your database. You enter the coffee name and price and save it.
Read:
Get data from the database.
Example: When you open your client site to look up coffee items, you read data from the database.
Update:
Change existing data in the database.
Example: If you want to change the coffee price, you can edit the coffee price to update the price.
Delete:
Remove data from the database.
Example: If you no longer need a coffee item, you can delete it from your database.
Yeeessss!!! Now we learned the basic operations,
Now we will understand CRUD operation by applying the code in express.js,
Setup and Middleware
const express = require('express');
const cors = require('cors');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
const app = express();
const port = process.env.PORT || 5000;
require('dotenv').config();
// Middleware
app.use(cors());
app.use(express.json());
Express Setup: Sets up the Express application.
cors: Middleware to enable Cross-Origin Resource Sharing, allowing the frontend to make requests to this server from different origins.
express.json(): Middleware to parse JSON request bodies.
MongoDB Connection Setup
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.2pzzeio.mongodb.net/?retryWrites=true&w=majority`;
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
MongoDB Connection: Uses the MongoClient from the MongoDB driver to connect to the MongoDB Atlas cluster using the connection string stored in the .env file.
CRUD Operations
app.get('/coffee', async (req, res) => {
const cursor = coffeeCollection.find();
const result = await cursor.toArray();
res.send(result);
});
GET /coffee: Retrieves all documents (coffees) from the coffee collection in the coffeeDB database.
GET Single Coffee
app.get('/coffee/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await coffeeCollection.findOne(query);
res.send(result);
});
GET /coffee/: Retrieves a single coffee by its _id. Uses ObjectId from MongoDB to create a query object.
PUT (Update) Coffee
app.put('/coffee/:id', async (req, res) => {
const id = req.params.id;
const filter = { _id: new ObjectId(id) };
const options = { upsert: true };
const updatedCoffee = req.body;
const coffee = {
$set: {
name: updatedCoffee.name,
quantity: updatedCoffee.quantity,
supplier: updatedCoffee.supplier,
taste: updatedCoffee.taste,
category: updatedCoffee.category,
details: updatedCoffee.details,
photo: updatedCoffee.photo,
}
};
const result = await coffeeCollection.updateOne(filter, coffee, options);
res.send(result);
});
POST /coffee: Inserts a new coffee document into the coffee collection using insertOne().
DELETE Coffee
app.delete('/coffee/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await coffeeCollection.deleteOne(query);
res.send(result);
});
DELETE /coffee/: Deletes a coffee by its _id using deleteOne().
Server Startup and Ping
app.get('/', (req, res) => {
res.send("Coffee making server is running...");
});
app.listen(port, () => {
console.log(`Coffee server is running on port: ${port}`);
});
GET /: Simple route to verify that the server is running.
Server Start: Starts the Express server on the specified port (5000 by default).
MongoDB Connection Management
The run() function is an asynchronous function that connects to MongoDB using await client.connect()
. It also sets up the coffeeCollection
variable to interact with the coffee collection in the coffeeDB database.
It uses MongoDB's findOne()
, find()
, updateOne()
, insertOne()
, and deleteOne()
methods to perform CRUD operations on the coffeeCollection.
Code Link: https://github.com/Praneshchow/Coffee-express-server
These operations are the basic actions that can be performed on any data set, whether it is contacts in your phone, products in an online store, or posts on a social media site.
Top comments (0)