跳至主要内容

2 篇文章 含有標籤「Express.js」

檢視所有標籤

MongoDB 入門教學筆記 | 學習筆記

· 閱讀時間約 4 分鐘
kdchang

前言

在現代應用程式開發中,資料儲存已不再侷限於傳統的關聯式資料庫(如 MySQL、PostgreSQL)。特別是在處理非結構化資料、需要高延展性或頻繁 schema 變動的應用場景中,NoSQL 資料庫逐漸成為主流選擇。

其中,MongoDB 是最受歡迎的 NoSQL 資料庫之一。它採用文件型(Document-Oriented)結構,使用 JSON 類型格式(實際為 BSON)儲存資料,讓開發者能更靈活地設計資料模型與操作資料。MongoDB 強調可擴展性、彈性資料結構與高效查詢能力,廣泛應用於 Web 開發、物聯網、大數據處理等領域。


重點摘要

  • MongoDB 是什麼?

    • 開源的 NoSQL 文件資料庫,使用 BSON 格式儲存資料。
    • 資料以「資料庫 → 集合(Collection)→ 文件(Document)」的層級組織。
    • 每個文件(Document)類似於 JSON 結構,支援巢狀資料與陣列。
  • 主要特性

    • 文件型資料儲存(更彈性且接近開發者熟悉的物件結構)
    • 無需預先定義 Schema,可動態變更欄位
    • 垂直與水平延展能力佳
    • 提供複寫與分片支援(Replica Set、Sharding)
    • 強大的查詢語言,支援索引、聚合、全文搜尋
  • 應用場景

    • RESTful API 後端儲存(如 Node.js + Express 專案)
    • 快速原型設計與資料模型測試
    • 高並發讀寫需求(例如留言板、商品評論系統)
    • 資料格式變動頻繁的場景(如 IoT 裝置紀錄)

安裝與啟動

1. 安裝 MongoDB(本機)

Mac 使用者(使用 Homebrew):

brew tap mongodb/brew
brew install mongodb-community@7.0
brew services start mongodb/brew/mongodb-community

Windows / Linux: 可前往 https://www.mongodb.com/try/download/community 下載對應版本。

2. 啟動 MongoDB

mongod

啟動成功後,預設會在 mongodb://localhost:27017 提供本地服務。

3. 開啟 Mongo Shell(或使用 MongoDB Compass GUI)

mongosh

進入後會看到互動式 shell 環境,開始操作你的資料庫。


MongoDB 基本操作(Shell 範例)

1. 建立 / 切換資料庫

use blog

2. 建立集合(Collection)與新增文件(Document)

db.posts.insertOne({
title: 'MongoDB 入門教學',
author: 'KD',
tags: ['database', 'nosql', 'mongodb'],
published: true,
created_at: new Date(),
});

插入文件時自動建立集合與資料庫。

3. 查詢文件

db.posts.find();
db.posts.find({ author: 'KD' });
db.posts.findOne({ published: true });

支援條件、邏輯查詢、排序、分頁等功能:

db.posts.find({ published: true }).sort({ created_at: -1 }).limit(5);

4. 更新文件

db.posts.updateOne({ title: 'MongoDB 入門教學' }, { $set: { published: false } });

支援 $set, $inc, $push, $unset 等更新操作符。

5. 刪除文件

db.posts.deleteOne({ title: 'MongoDB 入門教學' });

使用 Mongoose 操作(Node.js 範例)

在 Node.js 專案中,常使用 mongoose 封裝操作 MongoDB。

1. 安裝套件

npm install mongoose

2. 建立連線與定義模型

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/blog');

const postSchema = new mongoose.Schema({
title: String,
author: String,
tags: [String],
published: Boolean,
created_at: { type: Date, default: Date.now },
});

const Post = mongoose.model('Post', postSchema);

3. 實際使用範例

新增資料:

const newPost = new Post({
title: '用 Node.js 操作 MongoDB',
author: 'KD',
tags: ['nodejs', 'mongodb'],
published: true,
});

await newPost.save();

查詢資料:

const posts = await Post.find({ published: true }).limit(5);

更新資料:

await Post.updateOne({ title: '用 Node.js 操作 MongoDB' }, { published: false });

刪除資料:

await Post.deleteOne({ title: '用 Node.js 操作 MongoDB' });

聚合(Aggregation)入門

MongoDB 提供強大的 Aggregation Pipeline 功能,可進行統計、分組、轉換。

範例:統計作者貼文數量

db.posts.aggregate([{ $group: { _id: '$author', count: { $sum: 1 } } }, { $sort: { count: -1 } }]);

總結

MongoDB 以其彈性、易用與高延展性,成為許多現代應用的首選資料庫,特別是在快速開發、微服務架構或大數據處理場景中表現優異。透過簡單的 JSON 結構與強大的查詢能力,即使不熟 SQL 的開發者也能快速上手,打造穩定且具擴展性的資料儲存系統。

初學者可先從基本的增刪查改練習起,逐步熟悉資料結構與聚合操作,再延伸到使用 Mongoose 開發 REST API,或搭配 GraphQL、Next.js 等前後端整合工具,深入打造現代 Web 應用。

Node.js Express.js 入門教學筆記 | 學習筆記

· 閱讀時間約 3 分鐘
kdchang

1. 簡介

Express.js 是一個基於 Node.js 的 Web 應用框架,提供簡潔且靈活的 API,適用於建立伺服器端應用程式。它可以用來開發 RESTful API、Web 應用或後端服務。

為什麼選擇 Express.js?

  • 輕量且易於學習
  • 擴展性高
  • 內建強大的中介軟體(Middleware)系統
  • 支援各種範本引擎(例如:EJS, Pug)

2. 安裝與專案初始化

安裝 Node.js

在開始使用 Express.js 之前,請先安裝 Node.js

初始化專案

建立一個新的專案資料夾,然後執行以下指令來初始化 Node.js 專案:

mkdir express-app
cd express-app
npm init -y

安裝 Express.js

npm install express

3. 建立第一個 Express 伺服器

建立 server.js 檔案,並加入以下程式碼:

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
res.send('Hello, Express!');
});

app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});

啟動伺服器

node server.js

然後在瀏覽器打開 http://localhost:3000/,應該可以看到 Hello, Express!

4. 中介軟體(Middleware)

Express 提供 Middleware,可用來處理請求與回應,例如:解析請求體、驗證請求等。

使用 express.json() 解析 JSON

app.use(express.json());

建立自訂中介軟體

app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});

5. 路由(Routing)

Express 允許定義不同的 HTTP 方法對應不同的路由。

GET 路由

app.get('/api/users', (req, res) => {
res.json([{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]);
});

POST 路由

app.post('/api/users', (req, res) => {
const newUser = req.body;
res.status(201).json(newUser);
});

參數化路由

app.get('/api/users/:id', (req, res) => {
const userId = req.params.id;
res.json({ id: userId, name: `User ${userId}` });
});

6. 靜態檔案服務

Express 可用來提供靜態檔案,例如 HTML、CSS、JavaScript。

app.use(express.static('public'));

然後在 public/index.html 中放入 HTML,即可直接透過 http://localhost:3000/index.html 存取。

7. 錯誤處理

Express 提供錯誤處理中介軟體,可用來處理應用中的錯誤。

app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ message: 'Something went wrong!' });
});

8. 整合 MongoDB

可以使用 mongoose 來與 MongoDB 互動。

安裝 mongoose

npm install mongoose

連接 MongoDB

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB');
}).catch(err => {
console.error('MongoDB connection error:', err);
});

9. 部署 Express 應用

可以使用 PM2 來管理 Express 伺服器。

安裝 PM2

npm install -g pm2

啟動應用

pm2 start server.js --name express-app

10. 總結

透過這篇筆記,你已經學會:

  1. 安裝與初始化 Express.js
  2. 建立基本 Web 伺服器
  3. 使用中介軟體與路由
  4. 提供靜態檔案
  5. 錯誤處理
  6. 整合 MongoDB
  7. 部署 Express 應用

這些概念是 Express.js 開發的基礎,熟練後可以進一步學習 JWT 認證、WebSocket、GraphQL 等進階技術!