Home > Web Front-end > JS Tutorial > CRUD Operations with Express.js and MongoDB

CRUD Operations with Express.js and MongoDB

DDD
Release: 2024-12-20 14:34:14
Original
309 people have browsed it

CRUD Operations with Express.js and MongoDB

This guide explains how to implement CRUD (Create, Read, Update, Delete) operations using Express.js and MongoDB. CRUD is a fundamental concept for interacting with databases and is essential for most web applications.

Prerequisites

  • Basic knowledge of JavaScript, Node.js, and Express.js.
  • MongoDB installed locally or access to a MongoDB cloud service (e.g., MongoDB Atlas).
  • npm installed.

Project Setup

  1. Initialize a Node.js project:
   mkdir crud-express-mongodb
   cd crud-express-mongodb
   npm init -y
Copy after login
  1. Install dependencies:
   npm install express mongoose body-parser cors dotenv
Copy after login
  1. Create the following folder structure:
   crud-express-mongodb/
   |-- models/
   |-- routes/
   |-- .env
   |-- server.js
Copy after login

Step 1: Setup MongoDB Connection

File: .env

MONGO_URI=mongodb://localhost:27017/crudDB
PORT=5000
Copy after login

File: server.js

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv").config();

const app = express();

// Middleware
app.use(bodyParser.json());
app.use(cors());

// MongoDB Connection
mongoose
  .connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log("MongoDB Connected"))
  .catch((err) => console.error("MongoDB connection error:", err));

// Routes
const itemRoutes = require("./routes/itemRoutes");
app.use("/api/items", itemRoutes);

// Start Server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Copy after login

Step 2: Create a MongoDB Schema

File: models/Item.js

const mongoose = require("mongoose");

const itemSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
}, { timestamps: true });

module.exports = mongoose.model("Item", itemSchema);
Copy after login

Step 3: Implement CRUD Routes

File: routes/itemRoutes.js

const express = require("express");
const router = express.Router();
const Item = require("../models/Item");

// Create an item
router.post("/", async (req, res) => {
  try {
    const newItem = new Item(req.body);
    const savedItem = await newItem.save();
    res.status(201).json(savedItem);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Get all items
router.get("/", async (req, res) => {
  try {
    const items = await Item.find();
    res.status(200).json(items);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Get an item by ID
router.get("/:id", async (req, res) => {
  try {
    const item = await Item.findById(req.params.id);
    if (!item) return res.status(404).json({ error: "Item not found" });
    res.status(200).json(item);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Update an item by ID
router.put("/:id", async (req, res) => {
  try {
    const updatedItem = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!updatedItem) return res.status(404).json({ error: "Item not found" });
    res.status(200).json(updatedItem);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Delete an item by ID
router.delete("/:id", async (req, res) => {
  try {
    const deletedItem = await Item.findByIdAndDelete(req.params.id);
    if (!deletedItem) return res.status(404).json({ error: "Item not found" });
    res.status(200).json({ message: "Item deleted" });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;
Copy after login

Step 4: Testing the API

Use tools like Postman or cURL to test the following endpoints:

  1. Create an item:
   POST /api/items
   Content-Type: application/json
   {
     "name": "Laptop",
     "description": "A powerful laptop",
     "price": 1200
   }
Copy after login
  1. Get all items:
   GET /api/items
Copy after login
  1. Get an item by ID:
   GET /api/items/:id
Copy after login
  1. Update an item:
   PUT /api/items/:id
   Content-Type: application/json
   {
     "name": "Gaming Laptop",
     "description": "A high-end gaming laptop",
     "price": 1500
   }
Copy after login
  1. Delete an item:
   DELETE /api/items/:id
Copy after login

The above is the detailed content of CRUD Operations with Express.js and MongoDB. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template