昨天我們透過 MongoDB Driver 直接操作資料,雖然能完成 CRUD,但實務上卻有幾個痛點:
db.collection("users").find(...)
,程式缺乏結構,專案一大就會變得凌亂難維護。{ name: 123 }
也能存進資料庫,長期下來資料品質難以保證。為了解決這些問題,我們就需要 Mongoose。
它是一個 ODM (Object Data Modeling) 工具,幫助我們更安全、更有結構地操作 MongoDB。
createdAt
、updatedAt
欄位。npm install mongoose
import mongoose from "mongoose";
// 連線到 testdb
await mongoose.connect("mongodb://localhost:27017/testdb");
console.log("✅ 已連接 MongoDB with Mongoose");
// 建立 Schema
const userSchema = new mongoose.Schema({
name: { type: String, required: true }, // 必填欄位
age: { type: Number, min: 0 }, // 年齡必須 ≥ 0
email: { type: String, unique: true }, // 不能重複
createdAt: { type: Date, default: Date.now } // 預設值
});
// 建立 Model (對應到 MongoDB 的 users 集合)
const User = mongoose.model("User", userSchema);
const newUser = await User.create({
name: "Alice",
age: 25,
email: "alice@example.com"
});
console.log("✅ 新增使用者:", newUser);
const allUsers = await User.find(); // 查詢全部
const Alice = await User.findOne({ name: "Alice" }); // 查詢單筆
// 直接更新
await User.updateOne({ name: "Alice" }, { $set: { age: 26 } });
// OOP 方式更新
const alice = await User.findOne({ name: "Alice" });
alice.age = 27;
await alice.save();
await User.deleteOne({ name: "Alice" });
相較於 MongoDB Driver,Mongoose 提供:
db.collection(...)
。Mongoose 幫助我們把「資料存取」標準化與結構化,讓開發者能專注在 業務邏輯 而不是資料操作細節。
參考資料: