MySQL Sequelize & Express-Phần 1 :Cài đặt và tạo table
1.Sequelize là gì ?
Sequelize là một ORM dành cho Node.js.
Nó hỗ trợ bạn truy cập một cách dễ dàng đến PostgreSQL, MySQL, MariaDB, SQLite và MSSQL cùng với các tính năng như là relations, transaction, replication …
2.Cài đặt:
Tạo folder gốc:
mkdir nodejs-express-sequelize-mysql-demo cd nodejs-express-sequelize-mysql-demo npm init
Cài thư viện:
npm install express sequelize mysql2 body-parser cors --save
3.Cấu hình Express JS Web Server:
Tạo file server.js với nội dung như sau:
Run server:
node server.js
Test link:http://localhost:8081/
Kết quả:
{ "message": "Welcome to gacoder.info" }
4.Cấu hình MySQL Database và Sequelize
Tạo folder config
mkdir config
Tạo file db.config.js trong folder config:
module.exports = { HOST: "localhost", USER: "root", PASSWORD: "", DB: "testdb", dialect: "mysql", pool: { max: 5, min: 0, acquire: 30000, idle: 10000 } };
Tạo database tên: testdb
Ý nghĩa các tham số:
max -maximum number of connections permissible in a pool
min – minimum number of connections permissible in a pool
idle – maximum time, in terms of milliseconds, that a connection can be held idly before being released
acquire – maximum time, in terms of milliseconds, that the pool seeks to make the connection before an error message pops up on screen
5.Khởi tạo Sequelize:
Tạo folder models
Tạo file index.js trong folder models với nội dung:
const dbConfig = require("../config/db.config.js"); const Sequelize = require("sequelize"); const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, { host: dbConfig.HOST, dialect: dbConfig.dialect, operatorsAliases: 0, 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; db.news= require("./news.model.js")(sequelize, Sequelize); module.exports = db;
Open file server.js và thêm vào như sau:
... const app = express(); app.use(...); const db = require("./models"); db.sequelize.sync(); ...
File server.js hoàn chỉnh:
6.Tạo Sequelize Model:
Tạo file news.model.js trong folder models:
module.exports = (sequelize, Sequelize) => { const News = sequelize.define("news", { title: { type: Sequelize.STRING }, description: { type: Sequelize.STRING }, published: { type: Sequelize.BOOLEAN } }); return News; };
Một số kiểu dữ liệu phổ biến của Sequelize:
Sequelize.STRING // VARCHAR(255)
Sequelize.STRING(1234) // VARCHAR(1234)
Sequelize.STRING.BINARY // VARCHAR BINARY
Sequelize.TEXT // TEXT
Sequelize.INTEGER // INTEGER
Sequelize.BIGINT // BIGINT
Sequelize.BIGINT(11) // BIGINT(11)
Sequelize.FLOAT // FLOAT
Sequelize.FLOAT(11) // FLOAT(11)
Sequelize.FLOAT(11, 12) // FLOAT(11,12)
Sequelize.REAL // REAL Chỉ hỗ trợ PostgreSQL.
Sequelize.REAL(11) // REAL(11) Chỉ hỗ trợ PostgreSQL.
Sequelize.REAL(11, 12) // REAL(11,12) Chỉ hỗ trợ PostgreSQL.
Sequelize.DOUBLE // DOUBLE
Sequelize.DOUBLE(11) // DOUBLE(11)
Sequelize.DOUBLE(11, 12) // DOUBLE(11,12)
Sequelize.DECIMAL // DECIMAL
Sequelize.DECIMAL(10, 2) // DECIMAL(10,2)
Sequelize.DATE // DATETIME for mysql / sqlite, TIMESTAMP WITH TIME ZONE for postgres
Sequelize.BOOLEAN // TINYINT(1)
Sequelize.ENUM(‘value 1’, ‘value 2’)
Sequelize.ARRAY(Sequelize.TEXT) // Chỉ hỗ trợ PostgreSQL.
Sequelize.JSON // JSON column. Chỉ hỗ trợ PostgreSQL.
Sequelize.JSONB // JSONB column. Chỉ hỗ trợ PostgreSQL.
7.Run command để tạo table news trong database:
node server.js
Kết quả command:
Server is running on port 8081. Executing (default): CREATE TABLE IF NOT EXISTS `news` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255), `description` VARCHAR(255), `published` TINYINT(1) DEFAULT '0', `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB; Executing (default): SHOW INDEX FROM `news`
Table news đã tạo trong database:
Ở đây sequelize đã tự tạo cho ta 3 column:
Id:khóa chính
createdAt:time tạo
updatedAt:time cập nhật
Muốn tạo luôn khóa chính không dùng mặc định là id bạn sử dụng như sau trong file news.model.js:
user_id: { type: Sequelize.BIGINT, autoIncrement: true, primaryKey: true },
Link code demo here