const { Sequelize } = require('sequelize');
// 第一个参数:连接的数据库名
// 第二个参数:数据库的用户名
// 第三个参数:数据库的密码
const mysql = new Sequelize('mytest', 'root', 'root', {
dialect: 'mysql', // 这里可以改成任意一种关系型数据库
host: 'localhost', // 数据库服务器
timezone: '+08:00', // 这里是东八区,默认为0时区
pool: { // 使用连接池
max: 5,
min: 0,
acquire: 30000,
idle: 10000,
},
});
// 测试连接是否成功
(async () => {
try {
await mysql.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
})(); // 多一个括号表示调用方法
const AppConfig = {
environment: "dev",
database: {
database: "notes_app", // 库名
username: "notes_app", // 用户名
password: "notes_app", // 密码
options: {
// 配置
host: "localhost",
dialect: "mysql",
define: {
// create_time && update_time
timestamps: true,
// delete_time
paranoid: true,
createdAt: "created_at",
updatedAt: "updated_at",
deletedAt: "deleted_at",
// 把驼峰命名转换为下划线
underscored: true,
scopes: {
bh: {
attributes: {
exclude: ["updated_at", "deleted_at", "created_at"]
}
},
iv: {
attributes: {
exclude: ["updated_at", "deleted_at"]
}
}
}
},
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
timezone: "+08:00" // 东八时区
}
},
security: {
secretKey: "secretKey",
// 过期时间 1小时
expiresIn: 60 * 60
}
};
module.exports = AppConfig;
const { Sequelize } = require("sequelize");
const AppConfig = require("../config/config");
class DbManager {
constructor() {
this.config = AppConfig.database;
this.sequelize = null;
this.isConnected = false;
}
async isConnection() {
const { database, username, password, options } = this.config;
this.sequelize = new Sequelize(database, username, password, options);
try {
await this.sequelize.authenticate();
// console.log("successfully");
this.isInitOk = true;
return true;
} catch (error) {
console.error("Unable to connect to the database:", error);
return false;
}
}
start() {
const isConnected = this.isConnection();
this.isConnected = isConnected;
if (isConnected) {
// console.log("连接ok");
return true;
}
}
stop() {
if (this.sequelize !== null) {
this.sequelize.close();
console.log("连接close");
}
}
getSequelize() {
return this.sequelize;
}
getIsConnected() {
return this.isConnected;
}
}
const dbManager = new DbManager();
dbManager.start();
const sequelize = dbManager.getSequelize();
// console.log(sequelize);
sequelize.sync({ force: false }); // 初始化模型
module.exports = {
dbManager,
sequelize
};
Sequelize.STRING // VARCHAR(255)
Sequelize.STRING(1234) // VARCHAR(1234)
Sequelize.STRING.BINARY // VARCHAR BINARY
Sequelize.TEXT // TEXT
Sequelize.TEXT('tiny') // TINYTEXT
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 仅限于PostgreSQL.
Sequelize.REAL(11) // REAL(11) 仅限于PostgreSQL.
Sequelize.REAL(11, 12) // REAL(11,12) 仅限于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 针对 mysql / sqlite, TIMESTAMP WITH TIME ZONE 针对 postgres
Sequelize.DATE(6) // DATETIME(6) 针对 mysql 5.6.4+. 小数秒支持多达6位精度
Sequelize.DATEONLY // DATE 不带时间.
Sequelize.BOOLEAN // TINYINT(1)
Sequelize.ENUM('value 1', 'value 2') // 一个允许具有 “value 1” 和 “value 2” 的 ENUM
Sequelize.ARRAY(Sequelize.TEXT) // 定义一个数组。 仅限于 PostgreSQL。
Sequelize.ARRAY(Sequelize.ENUM) // 定义一个 ENUM 数组. 仅限于 PostgreSQL。
const { Model, DataTypes } = require("sequelize");
const { sequelize } = require("../util/db");
class Cate extends Model {}
Cate.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true, // 主键
autoIncrement: true // 自增
},
uid: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
unique: true // 唯一
},
name: DataTypes.STRING,
icon: DataTypes.STRING,
desc: DataTypes.TEXT,
parentUid: DataTypes.UUID
},
{
sequelize,
tableName: "cate" // 指定生成的表名
}
);
module.exports = {
Cate
};
Cate.sync({ force: false })
.then(async () => {
await Cate.create({
name: "所有笔记",
icon: " ",
desc: "所有笔记",
parentUid: ""
});
await Cate.create({
name: "标签",
icon: " ",
desc: "标签",
parentUid: ""
});
await Cate.create({
name: "回收站",
icon: " ",
desc: "回收站",
parentUid: ""
});
})
.catch(err => {
console.log("err= ", err);
}); // 初始化模型
class Article extends Model {}
Article.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true, // 主键
autoIncrement: true // 自增
},
uid: {
type: DataTypes.UUID,
primaryKey: true, // 主键
defaultValue: DataTypes.UUIDV4
},
title: DataTypes.STRING,
deleteUid: DataTypes.UUID,
collectUid: DataTypes.UUID,
publishStatus: {
type: DataTypes.INTEGER,
// (0草稿、1公开、2私有)
defaultValue: 0
}
},
{
sequelize,
tableName: "article" // 指定生成的表名
}
);
class ArticleContent extends Model {}
ArticleContent.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true, // 主键
autoIncrement: true // 自增
},
uid: {
type: DataTypes.UUID,
primaryKey: true, // 主键
defaultValue: DataTypes.UUIDV4
},
content: DataTypes.TEXT
},
{
sequelize,
timestamps: false,
tableName: "article_content" // 指定生成的表名
}
);
// 关联意味着 A 和 B 之间存在一对一的关系,外键在目标模型(B)中定义.
ArticleContent.hasOne(Article, {
foreignKey: "article_content_uid",
sourceKey: "uid"
});
// A.belongsTo(B)关联意味着 A 和 B 之间存在一对一的关系,外键在源模型中定义(A).
Article.belongsTo(ArticleContent, {
foreignKey: "article_content_uid",
sourceKey: "uid"
});
class Cate extends Model {}
Cate.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true, // 主键
autoIncrement: true // 自增
},
uid: {
type: DataTypes.UUID,
primaryKey: true, // 主键
defaultValue: DataTypes.UUIDV4
},
name: DataTypes.STRING,
icon: DataTypes.STRING,
desc: DataTypes.TEXT,
parentUid: DataTypes.UUID
},
{
sequelize,
tableName: "cate" // 指定生成的表名
}
);
class ArticleCates extends Model {}
ArticleCates.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true, // 主键
allowNull: false,
autoIncrement: true // 自增
},
uid: {
type: DataTypes.UUID,
primaryKey: true, // 主键
defaultValue: DataTypes.UUIDV4
}
},
{
sequelize,
timestamps: false,
tableName: "articale_cates" // 指定生成的表名
}
);
Article.hasMany(ArticleCates, {
foreignKey: "article_uid",
sourceKey: "uid"
});
Cate.hasMany(ArticleCates, {
foreignKey: "cate_uid",
sourceKey: "uid"
});
ArticleCates.belongsTo(Article, { foreignKey: "article_uid" });
ArticleCates.belongsTo(Cate, { foreignKey: "cate_uid" });
如果采用多对多方式关联,始终都关联不上uid,可以用id关联。
Article.belongsToMany(Cate, {
through: ArticleCates,
foreignKey: "article_uid", // ArticleCates 表中表示文章 uid 的字段名
sourceKey: "uid",
otherKey: "cate_uid" // ArticleCates 表中表示分类 uid 的字段名
});
Cate.belongsToMany(Article, {
through: ArticleCates,
foreignKey: "cate_uid", // ArticleCates 表中表示分类 uid 的字段名
sourceKey: "uid",
otherKey: "article_uid" // ArticleCates 表中表示文章 uid 的字段名
});