เนื้อหาดังต่อไปนี้เป็นเนื้อหาเมื่อปี 2023 ถูกปรับปรุงเรียบเรียงใหม่ 2026 ขอให้สนุกกับการเริ่มต้นกับโลก Programming อย่างภาษาง่าย ๆ ด้วย JavaScript กันเน่อ :)
📖 คำนำ
เอกสารฉบับนี้เป็นการพัฒนา web service หรือ RESTful API โดยใช้ภาษา JavaScript Node.js ร่วมกับเฟรมเวิร์กและไลบรารี่ต่าง ๆ ได้แก่:
- 🌐 Express HTTP Framework - สำหรับสร้าง web server
- 🗄️ Sequelize - ORM สำหรับจัดการฐานข้อมูล
- 💾 MySQL - ฐานข้อมูลเชิงสัมพันธ์
- 🔧 POSTMAN - สำหรับทดสอบ API
Module 3: 🗄️ Sequelize
เรียนรู้การใช้ Sequelize ORM สำหรับจัดการฐานข้อมูล
Section 3-1 - 📦 การติดตั้ง Sequelize
📥 ติดตั้ง Sequelize
Sequelize เป็น ORM (Object-Relational Mapping) ที่ช่วยให้เราจัดการฐานข้อมูลได้ง่ายขึ้น
npm install --save sequelize
📚 เอกสารเพิ่มเติม: ดูข้อมูลเพิ่มเติมได้ที่ Sequelize Documentation
🔌 ติดตั้ง Database Driver
เราต้องติดตั้ง driver สำหรับฐานข้อมูลที่เราจะใช้ด้วยนะครับ
| Database | Driver Package | คำสั่งติดตั้ง |
|---|---|---|
| PostgreSQL |
pg, pg-hstore
|
npm install --save pg pg-hstore |
| MySQL | mysql2 |
npm install --save mysql2 |
| MariaDB | mariadb |
npm install --save mariadb |
| SQLite | sqlite3 |
npm install --save sqlite3 |
| Microsoft SQL Server | tedious |
npm install --save tedious |
| Oracle Database | oracledb |
npm install --save oracledb |
💡 ตัวอย่างสำหรับ MySQL (ที่เราจะใช้ในบทเรียนนี้):
npm install --save sequelize mysql2
Section 3-2 - 🚀 New Project for Sequelize Demo
📁 สร้างโปรเจกต์ใหม่
1. สร้างโปรเจกต์ Node.js
npm init -y
2. ติดตั้ง Packages ที่จำเป็น
npm install express mysql2 cors sequelize
npm install -D nodemon
📋 Packages ที่ติดตั้ง:
| Package | Description |
|---|---|
express |
Web framework |
mysql2 |
MySQL driver สำหรับ Sequelize |
cors |
Cross-Origin Resource Sharing middleware |
sequelize |
ORM สำหรับจัดการฐานข้อมูล |
nodemon |
Auto-restart server (dev dependency) |
📄 สร้างไฟล์ server.js
ไฟล์: server.js
const express = require('express')
const app = express();
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
const PORT = process.env.PORT || 5000
app.get('/', (req, res) => {
res.json({ message: "Welcome to my app" })
})
app.listen(PORT, () => {
console.log(`SERVER ON PORT ${PORT}`)
})
▶️ รันแอปพลิเคชัน
nodemon server.js
หรือเพิ่ม script ใน package.json:
{
"scripts": {
"dev": "nodemon server.js"
}
}
แล้วรันด้วย:
npm run dev
Section 3-3 - ⚙️ Config Sequelize
📁 สร้างโฟลเดอร์และไฟล์ Config
1. สร้างโฟลเดอร์ config
mkdir config
2. สร้างไฟล์ db.config.js
ไฟล์: config/db.config.js
module.exports = {
DB_HOST: "localhost",
DB_USERNAME: "root",
DB_PASSWORD: "",
DB_DATABASE: "db_std",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
🔍 อธิบาย Config:
-
DB_HOST- ที่อยู่ของ MySQL server -
DB_USERNAME- ชื่อผู้ใช้ MySQL -
DB_PASSWORD- รหัสผ่าน MySQL -
DB_DATABASE- ชื่อฐานข้อมูล -
dialect- ประเภทฐานข้อมูล (mysql, postgres, sqlite, etc.) -
pool- การตั้งค่า connection pool
📄 สร้างไฟล์ models/index.js
ไฟล์นี้จะใช้สำหรับเชื่อมต่อ Sequelize กับฐานข้อมูลและ register models
ไฟล์: models/index.js
const dbConfig = require("../config/db.config.js");
const Sequelize = require("sequelize");
const sequelize = new Sequelize(
dbConfig.DB_DATABASE,
dbConfig.DB_USERNAME,
dbConfig.DB_PASSWORD,
{
host: dbConfig.DB_HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
}
);
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
// Register models here
// db.students = require("./student.model.js")(sequelize, Sequelize);
// db.faculty = require("./faculty.model.js")(sequelize, Sequelize);
module.exports = db;
💡 หมายเหตุ: เราจะ register models ในขั้นตอนถัดไปนะครับ
🔄 Sync Database ใน server.js
ไฟล์: server.js
const express = require('express')
const app = express();
const db = require("./models");
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
const PORT = process.env.PORT || 5000
app.get('/', (req, res) => {
res.json({ message: "Welcome to my app" })
})
// Sync database
db.sequelize.sync({ force: false })
.then(() => {
console.log("Database was synchronized successfully.");
app.listen(PORT, () => {
console.log(`SERVER ON PORT ${PORT}`)
})
})
.catch((err) => {
console.log("Failed to synchronize database: " + err.message);
});
🔍 อธิบาย sync():
-
force: false- ไม่ลบตารางที่มีอยู่แล้ว (ใช้trueเพื่อลบและสร้างใหม่) -
sync()- สร้างตารางตาม models ที่เรากำหนด
Section 3-4 - 📋 สร้างโมเดล Student และ Faculty
🏛️ สร้างโมเดล Faculty
ไฟล์: models/faculty.model.js
module.exports = (sequelize, Sequelize) => {
const Faculty = sequelize.define("faculty", {
facultyId: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
field: "fac_id"
},
facultyName: {
type: Sequelize.STRING,
field: "fac_name",
},
}, {
sequelize,
tableName: 'faculty',
freezeTableName: true,
timestamps: false
});
Faculty.associate = (models) => {
Faculty.hasMany(models.student, {
foreignKey: 'fac_id',
sourceKey: 'fac_id',
onDelete: "cascade",
});
}
return Faculty;
}
🔍 อธิบายโค้ด:
-
sequelize.define()- สร้างโมเดลใหม่ -
primaryKey: true- กำหนดเป็น primary key -
autoIncrement: true- เพิ่มค่า id อัตโนมัติ -
field: "fac_id"- กำหนดชื่อคอลัมน์ในฐานข้อมูล -
freezeTableName: true- ใช้ชื่อตารางตามที่กำหนด (ไม่เติม 's') -
timestamps: false- ไม่ใช้ created_at และ updated_at -
hasMany()- กำหนดความสัมพันธ์ one-to-many (1 คณะมีหลายนักศึกษา)
👨🎓 สร้างโมเดล Student
ไฟล์: models/student.model.js
module.exports = (sequelize, Sequelize) => {
const Student = sequelize.define("student", {
stdId: {
primaryKey: true,
type: Sequelize.STRING,
field: "std_id",
},
stdPass: {
type: Sequelize.STRING,
field: "std_pass",
},
stdName: {
type: Sequelize.STRING,
field: "std_name",
},
facId: {
type: Sequelize.INTEGER,
field: "fac_id",
unique: false
},
}, {
sequelize,
tableName: 'student',
freezeTableName: true,
timestamps: false
});
Student.associate = (models) => {
Student.belongsTo(models.faculty, {
foreignKey: 'fac_id',
sourceKey: 'fac_id',
onDelete: "cascade",
});
}
return Student;
};
🔍 อธิบายโค้ด:
-
belongsTo()- กำหนดความสัมพันธ์ many-to-one (หลายนักศึกษาอยู่ใน 1 คณะ) -
onDelete: "cascade"- เมื่อลบ faculty จะลบ student ที่เกี่ยวข้องด้วย
📝 Register Models ใน models/index.js
หลังจากสร้างโมเดลแล้ว เราต้อง register ใน models/index.js นะครับ
ไฟล์: models/index.js
const dbConfig = require("../config/db.config.js");
const Sequelize = require("sequelize");
const sequelize = new Sequelize(
dbConfig.DB_DATABASE,
dbConfig.DB_USERNAME,
dbConfig.DB_PASSWORD,
{
host: dbConfig.DB_HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
}
);
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
// Register models
db.students = require("./student.model.js")(sequelize, Sequelize);
db.faculty = require("./faculty.model.js")(sequelize, Sequelize);
// Initialize associations
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
module.exports = db;
🔍 จุดสำคัญ:
- Register models ก่อนใช้
- เรียก
associate()เพื่อกำหนดความสัมพันธ์ระหว่างโมเดล
Section 3-5 - 🎮 การสร้าง Controllers
📁 สร้างโฟลเดอร์ Controllers
mkdir controllers
🏛️ สร้าง Faculty Controller
ไฟล์: controllers/faculty.controller.js
const db = require('../models')
const facultyModel = db.faculty;
const Op = db.Sequelize.Op;
// Get all faculty
exports.findAll = async (req, res) => {
try {
const response = await facultyModel.findAll()
res.status(200).json({
message: "get all faculty was successfully",
payload: response
})
} catch (error) {
res.status(500).json({
message: error.message || "get all faculty was failed"
})
}
}
🔍 อธิบายโค้ด:
-
facultyModel.findAll()- ดึงข้อมูล faculty ทั้งหมด -
async/await- ใช้ async function เพื่อจัดการ Promise -
try/catch- จัดการ error
👨🎓 สร้าง Student Controller
ไฟล์: controllers/student.controller.js
const db = require('../models')
const studentModel = db.students;
// Get all student
exports.findAll = async (req, res) => {
try {
const response = await studentModel.findAll()
res.status(200).json({
message: "get all student was successfully",
payload: response
})
} catch (error) {
res.status(500).json({
message: error.message || "get all student was failed"
})
}
}
💡 หมายเหตุ: ใช้
db.students(มี s) ตามที่ register ในmodels/index.jsนะครับ
Section 3-6 - 🛣️ การสร้าง Faculty Routes
📁 สร้างโฟลเดอร์ Routes
mkdir routes
🏛️ สร้าง Faculty Route
ไฟล์: routes/faculty.route.js
const express = require("express");
const router = express.Router();
const facultyController = require("../controllers/faculty.controller");
router.get("/", facultyController.findAll);
module.exports = router;
🔍 อธิบายโค้ด:
-
express.Router()- สร้าง router instance -
router.get("/", ...)- สร้าง GET route ที่ path/ -
facultyController.findAll- เรียกใช้ controller function
🔗 เพิ่ม Route ใน server.js
ไฟล์: server.js
const express = require('express')
const app = express();
const db = require("./models");
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
const PORT = process.env.PORT || 5000
app.get('/', (req, res) => {
res.json({ message: "Welcome to my app" })
})
// Faculty routes
const facultyRoute = require("./routes/faculty.route");
app.use("/api/faculty", facultyRoute);
// Sync database
db.sequelize.sync({ force: false })
.then(() => {
console.log("Database was synchronized successfully.");
app.listen(PORT, () => {
console.log(`SERVER ON PORT ${PORT}`)
})
})
.catch((err) => {
console.log("Failed to synchronize database: " + err.message);
});
🧪 ทดสอบ API
GET http://localhost:5000/api/faculty
Section 3-7 - 🛣️ การสร้าง Student Routes
👨🎓 สร้าง Student Route
ไฟล์: routes/student.route.js
const express = require("express");
const router = express.Router();
const studentController = require("../controllers/student.controller");
router.get("/", studentController.findAll);
module.exports = router;
🔗 เพิ่ม Route ใน server.js
ไฟล์: server.js
const express = require('express')
const app = express();
const db = require("./models");
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
const PORT = process.env.PORT || 5000
app.get('/', (req, res) => {
res.json({ message: "Welcome to my app" })
})
// Faculty routes
const facultyRoute = require("./routes/faculty.route");
app.use("/api/faculty", facultyRoute);
// Student routes
const studentRoute = require("./routes/student.route");
app.use("/api/student", studentRoute);
// Sync database
db.sequelize.sync({ force: false })
.then(() => {
console.log("Database was synchronized successfully.");
app.listen(PORT, () => {
console.log(`SERVER ON PORT ${PORT}`)
})
})
.catch((err) => {
console.log("Failed to synchronize database: " + err.message);
});
🧪 ทดสอบ API
GET http://localhost:5000/api/student
Section 3-8 - ➕ การสร้าง Routes เพิ่มเติมใน Faculty (CRUD Complete)
➕ สร้าง Function createOne ใน Controller
เพิ่มในไฟล์: controllers/faculty.controller.js
exports.createOne = async (req, res) => {
try {
const response = await facultyModel.create(req.body)
res.status(201).json({
message: "create one faculty was successfully",
payload: response
})
} catch (error) {
res.status(500).json({
message: error.message || "create one faculty was failed"
})
}
}
🔍 อธิบายโค้ด:
-
facultyModel.create()- สร้าง record ใหม่ในฐานข้อมูล -
req.body- ข้อมูลที่ส่งมาจาก client -
status(201)- HTTP status code สำหรับการสร้างข้อมูลสำเร็จ
🔗 เพิ่ม Route สำหรับ Create
เพิ่มในไฟล์: routes/faculty.route.js
router.post("/", facultyController.createOne);
📝 ตัวอย่างโค้ดเต็ม faculty.route.js (หลังจากเพิ่ม POST)
const express = require("express");
const router = express.Router();
const facultyController = require("../controllers/faculty.controller");
router.get("/", facultyController.findAll);
router.post("/", facultyController.createOne);
module.exports = router;
🧪 ทดสอบ API
POST http://localhost:5000/api/faculty
Content-Type: application/json
{
"facultyName": "คณะวิศวกรรมศาสตร์"
}
✏️ สร้าง Function update ใน Controller
เพิ่มในไฟล์: controllers/faculty.controller.js
exports.update = async (req, res) => {
try {
const id = req.params.id
const body = req.body
const response = await facultyModel.update(body, {
where: { fac_id: id },
})
if (response[0] == 1) {
res.status(200).json({
message: "update one faculty was successfully",
payload: response
})
} else {
res.status(400).json({
message: `update one faculty was failed faculty with fac_id=${id}. Maybe fac was not found or req.body is empty!`
});
}
} catch (error) {
res.status(500).json({
message: error.message || "update one faculty was failed"
})
}
}
🔍 อธิบายโค้ด:
-
facultyModel.update()- อัปเดตข้อมูลในฐานข้อมูล -
where: { fac_id: id }- เงื่อนไขการค้นหา
- response[0] - จำนวนแถวที่ถูกอัปเดต (1 = สำเร็จ, 0 = ไม่พบข้อมูล)
🔗 เพิ่ม Route สำหรับ Update
เพิ่มในไฟล์: routes/faculty.route.js
router.put("/:id", facultyController.update);
🧪 ทดสอบ API
PUT http://localhost:5000/api/faculty/1
Content-Type: application/json
{
"facultyName": "คณะวิศวกรรมศาสตร์ (แก้ไข)"
}
🗑️ สร้าง Function delete ใน Controller
เพิ่มในไฟล์: controllers/faculty.controller.js
exports.delete = async (req, res) => {
try {
const id = req.params.id;
const response = await facultyModel.destroy({
where: {
fac_id: id
}
})
if (response == 1) {
res.status(200).json({
message: "delete faculty was successfully",
payload: response
})
} else {
res.status(400).json({
message: `delete faculty was failed faculty with fac_id=${id}. Maybe faculty was not found!`
});
}
} catch (error) {
res.status(500).json({
message: error.message || "delete faculty was failed"
})
}
}
🔍 อธิบายโค้ด:
-
facultyModel.destroy()- ลบข้อมูลจากฐานข้อมูล -
response == 1- จำนวนแถวที่ถูกลบ (1 = สำเร็จ, 0 = ไม่พบข้อมูล)
🔗 เพิ่ม Route สำหรับ Delete
เพิ่มในไฟล์: routes/faculty.route.js
router.delete("/:id", facultyController.delete);
📝 ตัวอย่างโค้ดเต็ม faculty.controller.js (CRUD Complete)
ไฟล์: controllers/faculty.controller.js
const db = require('../models')
const facultyModel = db.faculty;
const Op = db.Sequelize.Op;
// Get all faculty
exports.findAll = async (req, res) => {
try {
const response = await facultyModel.findAll()
res.status(200).json({
message: "get all faculty was successfully",
payload: response
})
} catch (error) {
res.status(500).json({
message: error.message || "get all faculty was failed"
})
}
}
// Create faculty
exports.createOne = async (req, res) => {
try {
const response = await facultyModel.create(req.body)
res.status(201).json({
message: "create one faculty was successfully",
payload: response
})
} catch (error) {
res.status(500).json({
message: error.message || "create one faculty was failed"
})
}
}
// Update faculty
exports.update = async (req, res) => {
try {
const id = req.params.id
const body = req.body
const response = await facultyModel.update(body, {
where: { fac_id: id },
})
if (response[0] == 1) {
res.status(200).json({
message: "update one faculty was successfully",
payload: response
})
} else {
res.status(400).json({
message: `update one faculty was failed faculty with fac_id=${id}. Maybe fac was not found or req.body is empty!`
});
}
} catch (error) {
res.status(500).json({
message: error.message || "update one faculty was failed"
})
}
}
// Delete faculty
exports.delete = async (req, res) => {
try {
const id = req.params.id;
const response = await facultyModel.destroy({
where: {
fac_id: id
}
})
if (response == 1) {
res.status(200).json({
message: "delete faculty was successfully",
payload: response
})
} else {
res.status(400).json({
message: `delete faculty was failed faculty with fac_id=${id}. Maybe faculty was not found!`
});
}
} catch (error) {
res.status(500).json({
message: error.message || "delete faculty was failed"
})
}
}
📝 ตัวอย่างโค้ดเต็ม faculty.route.js (CRUD Complete)
ไฟล์: routes/faculty.route.js
const express = require("express");
const router = express.Router();
const facultyController = require("../controllers/faculty.controller");
router.get("/", facultyController.findAll);
router.post("/", facultyController.createOne);
router.put("/:id", facultyController.update);
router.delete("/:id", facultyController.delete);
module.exports = router;
🧪 ทดสอบ API
DELETE http://localhost:5000/api/faculty/1
🎉 สรุป Module 3
เราได้เรียนรู้การใช้งาน Sequelize ORM ครบทั้ง:
| ฟีเจอร์ | คำอธิบาย |
|---|---|
| 📦 ติดตั้ง Sequelize | ติดตั้ง ORM และ database driver |
| ⚙️ Config Database | ตั้งค่าการเชื่อมต่อฐานข้อมูล |
| 📋 สร้าง Models | สร้างโมเดลและความสัมพันธ์ |
| 🎮 Controllers | สร้าง business logic |
| 🛣️ Routes | สร้าง API endpoints |
| 🔄 CRUD Operations | Create, Read, Update, Delete |
**🎊 ยินดีด้วยครับ! เราได้เรียนรู้การใช้งาน Sequelize ORM แล้ว** • [➡️ ไปยัง Module 4: Authorization with JWT](#module-4--authorization-with-jwt)
สร้าง controller สำหรับ findOne ใน faculty.controller.js
exports.findOne = async (req, res) => {
try {
const id = req.params.id
const response = await facultyModel.findOne({
where: { fac_id: id }
})
console.log(facultyModel)
res.status(200).json({
message: "get one faculty was successfully",
payload: response
})
} catch (error) {
res.status(500).json({
message: error.message || "get one faculty was failed"
})
}
}
สร้าง route สำหรับ findOne ใน faculty.route.js
router.get("/:id", facultyController.findOne)
Section 3-9 - 👨🎓 การสร้าง Controller & Route สำหรับ CRUD Student
📝 สร้าง Function findOne ใน Student Controller
เพิ่มในไฟล์: controllers/student.controller.js
// Get student by id
exports.findOne = async (req, res) => {
try {
const id = req.params.id
const response = await studentModel.findOne({
where: { std_id: id }
})
if (response) {
res.status(200).json({
message: "get one student was successfully",
payload: response
})
} else {
res.status(404).json({
message: "Student not found"
})
}
} catch (error) {
res.status(500).json({
message: error.message || "get one student was failed"
})
}
}
🔗 เพิ่ม Route สำหรับ findOne
เพิ่มในไฟล์: routes/student.route.js
router.get("/:id", studentController.findOne);
📝 ตัวอย่างโค้ดเต็ม student.controller.js (CRUD Complete)
ไฟล์: controllers/student.controller.js
const db = require('../models')
const studentModel = db.students;
// Get all students
exports.findAll = async (req, res) => {
try {
const response = await studentModel.findAll()
res.status(200).json({
message: "get all student was successfully",
payload: response
})
} catch (error) {
res.status(500).json({
message: error.message || "get all student was failed"
})
}
}
// Get student by id
exports.findOne = async (req, res) => {
try {
const id = req.params.id
const response = await studentModel.findOne({
where: { std_id: id }
})
if (response) {
res.status(200).json({
message: "get one student was successfully",
payload: response
})
} else {
res.status(404).json({
message: "Student not found"
})
}
} catch (error) {
res.status(500).json({
message: error.message || "get one student was failed"
})
}
}
📝 ตัวอย่างโค้ดเต็ม student.route.js (CRUD Complete)
ไฟล์: routes/student.route.js
const express = require("express");
const router = express.Router();
const studentController = require("../controllers/student.controller");
router.get("/", studentController.findAll);
router.get("/:id", studentController.findOne);
module.exports = router;
🧪 ทดสอบ API
GET http://localhost:5000/api/student
GET http://localhost:5000/api/student/12345
NodeJS 101 — Part 4 🔐 Authorization with JWT
Akkarapon Phikulsri ・ Jan 8
Reference
akkaraponph
/
basic-nodejs-express-sequelize-mysql
สร้าง API โดยใช้ JavaScript Node.js Express
หมายเหตุ Tutorial นี้ได้จัดทำขึ้นเมื่อ (April 4th, 2023) และได้รับการปรับปรุงเมื่อ (January 8th, 2026)
🚀 การสร้าง API โดยใช้ JavaScript Node.js Express
คู่มือการพัฒนา RESTful API แบบครบวงจรด้วย Node.js, Express, Sequelize และ MySQL
📖 คำนำ
เอกสารฉบับนี้เป็นการพัฒนา web service หรือ RESTful API โดยใช้ภาษา JavaScript Node.js ร่วมกับเฟรมเวิร์กและไลบรารี่ต่าง ๆ ได้แก่:
- 🌐 Express HTTP Framework - สำหรับสร้าง web server
- 🗄️ Sequelize - ORM สำหรับจัดการฐานข้อมูล
- 💾 MySQL - ฐานข้อมูลเชิงสัมพันธ์
- 🔧 POSTMAN - สำหรับทดสอบ API
📚 สารบัญ
- Section 1-1 - 🎯 Intro
- Section 1-2 - 🛣️ สร้าง Route ด้วย Express
- Section 1-3 - 💡 ตัวอย่างการสร้าง API
- Section 1-4 - ⚙️ การสร้าง Scripts
- Section 1-5 - 🔄 RESTful API
- Section 1-6 - 📥 Method GET and API Params
- Section 1-7 - 📤 Using JSON and Method POST
- Section 1-8 - ✏️ Method PUT
- Section 1-9 - 🗑️ Method DELETE

Top comments (0)