本指南介紹如何使用 Express.js 和 MongoDB 實作 CRUD(建立、讀取、更新、刪除)操作。 CRUD 是與資料庫互動的基本概念,對於大多數 Web 應用程式來說至關重要。
mkdir crud-express-mongodb cd crud-express-mongodb npm init -y
npm install express mongoose body-parser cors dotenv
crud-express-mongodb/ |-- models/ |-- routes/ |-- .env |-- server.js
MONGO_URI=mongodb://localhost:27017/crudDB PORT=5000
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}`));
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);
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;
使用 Postman 或 cURL 等工具來測試以下端點:
POST /api/items Content-Type: application/json { "name": "Laptop", "description": "A powerful laptop", "price": 1200 }
GET /api/items
GET /api/items/:id
PUT /api/items/:id Content-Type: application/json { "name": "Gaming Laptop", "description": "A high-end gaming laptop", "price": 1500 }
DELETE /api/items/:id
以上是使用 Express.js 和 MongoDB 進行 CRUD 操作的詳細內容。更多資訊請關注PHP中文網其他相關文章!