NoSQL คือกลุ่มฐานข้อมูลที่ไม่ยึดโครงสร้างตารางเชิงสัมพันธ์แบบ SQL เสมอไป โดย MongoDB เป็น Document Database ที่เก็บข้อมูลเป็น JSON-like หรือ BSON และ Mongoose เป็น ODM สำหรับใช้งาน MongoDB ใน Node.js
%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart LR
subgraph Era1["ยุค Relational First / SQL Dominant"]
A["Table + Row
schema คงที่"]
end
subgraph Era2["ยุค Web Scale / NoSQL"]
B["Document DB
JSON-like"]
C["MongoDB
Collection/Document"]
end
subgraph Era3["ยุค ODM / App Integration"]
D["Mongoose Schema
กำหนดรูปแบบ document"]
E["MongoDB Atlas
Cloud Database"]
end
A --> B --> C --> D --> E
new Schema({ name: String, age: Number, createdAt: Date })find(), findById(), create(), findByIdAndUpdate(), deleteOne()| หัวข้อ | SQL | NoSQL/MongoDB |
|---|---|---|
| โครงสร้าง | Table, Row, Column | Collection, Document, Field |
| Schema | ชัดเจนและเข้มงวด | ยืดหยุ่นกว่า |
| Relationship | JOIN เด่น | Embed หรือ Reference |
| Transaction | แข็งแรง | รองรับ แต่ใช้ตามกรณี |
| เหมาะกับ | ข้อมูลสัมพันธ์ชัดเจน | ข้อมูลเปลี่ยนรูปแบบบ่อย |
%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart TD
A["Database
ฐานข้อมูล"] --> B["Collection: users
กลุ่มเอกสาร"]
B --> C["Document
{ name, age }"]
B --> D["Document
{ name, courses[] }"]
C --> E["Field
key-value"]
// mongoose-demo.mjs
// ใช้ Mongoose เชื่อมต่อ MongoDB และสร้าง Model
import mongoose from 'mongoose';
await mongoose.connect(process.env.MONGO_URL || 'mongodb://localhost:27017/course');
const lessonSchema = new mongoose.Schema({
title: { type: String, required: true },
level: { type: String, default: 'beginner' },
createdAt: { type: Date, default: Date.now }
});
const Lesson = mongoose.model('Lesson', lessonSchema);
const created = await Lesson.create({
title: 'MongoDB Basics'
});
const lessons = await Lesson.find({ level: 'beginner' });
await Lesson.findByIdAndUpdate(created._id, {
title: 'MongoDB and Mongoose'
});
console.log(lessons);
await mongoose.disconnect();
// ตัวอย่างการใช้งาน:
// npm install mongoose
// MONGO_URL=mongodb://localhost:27017/course node mongoose-demo.mjs
Lessoncreate()find()