第6篇:EggJS数据库操作与ORM实践
在Web应用开发中,数据库操作是核心环节之一。EggJS通过集成Sequelize ORM框架,提供了高效、安全的数据库操作方案。本文将深入讲解如何在EggJS中配置MySQL数据库、定义数据模型、优化复杂查询,以及管理数据库迁移与种子数据。
一、MySQL基础配置与多环境适配
1. 安装与基础配置
安装Egg-Sequelize插件:
npm install egg-sequelize mysql2 --save
配置数据库连接(config/config.default.js
):
module.exports = {sequelize: {dialect: 'mysql',host: '127.0.0.1',port: 3306,username: 'root',password: 'your_password',database: 'egg_demo',timezone: '+08:00', // 设置时区define: {freezeTableName: true, // 禁止自动修改表名timestamps: false // 禁用默认时间戳字段}}
};
2. 多环境配置策略
使用EggJS环境配置机制:
config
├── config.default.js
├── config.prod.js
└── config.unittest.js
生产环境配置示例(config/config.prod.js
):
const { GetDatabaseConfig } = require('./utils/config-loader');module.exports = {sequelize: {...GetDatabaseConfig('prod'), // 从安全存储获取配置pool: { // 连接池配置max: 5,min: 1,idle: 10000}}
};
安全建议:
- 敏感信息通过环境变量注入
- 生产配置使用加密存储方案
- 不同环境完全隔离数据库实例
二、Sequelize模型定义与关联关系
1. 基础模型定义
创建用户模型(app/model/user.js
):
module.exports = app => {const { STRING, INTEGER, DATE } = app.Sequelize;const User = app.model.define('user', {id: { type: INTEGER, primaryKey: true, autoIncrement: true },username: { type: STRING(30), unique: true },password: { type: STRING(64) },created_at: DATE,updated_at: DATE});return User;
};
2. 关联关系类型
一对多关系(用户-文章):
// app/model/user.js
User.associate = function() {this.hasMany(app.model.Article, { foreignKey: 'author_id' });
};// app/model/article.js
Article.associate = function() {this.belongsTo(app.model.User, { foreignKey: 'author_id' });
};
多对多关系(文章-标签):
// app/model/article.js
Article.associate = function() {this.belongsToMany(app.model.Tag, {through: 'article_tag',foreignKey: 'article_id'});
};
三、复杂查询构建与性能优化
1. 高级查询示例
分页查询+关联数据:
async listArticles(page = 1, pageSize = 10) {const { count, rows } = await ctx.model.Article.findAndCountAll({offset: (page - 1) * pageSize,limit: pageSize,include: [{ model: ctx.model.User, attributes: ['id', 'username'] },{ model: ctx.model.Tag, through: { attributes: [] } }],order: [['created_at', 'DESC']]});return { total: count, list: rows };
}
2. 性能优化策略
索引优化:
// 模型定义时添加索引
Article.init({title: {type: STRING(100),index: true // 普通索引}
}, { sequelize });
避免N+1查询:
// 错误做法
const articles = await Article.findAll();
for (const article of articles) {const user = await article.getUser(); // 产生N次查询
}// 正确做法
const articles = await Article.findAll({include: [User]
});
慢查询监控:
// config/config.default.js
sequelize: {logging: (sql, timing) => {if (timing > 200) { // 记录超过200ms的查询app.logger.warn(`Slow query (${timing}ms): ${sql}`);}}
}
四、数据库迁移与种子数据管理
1. 使用迁移工具
安装迁移模块:
npm install umzug --save-dev
创建迁移文件(database/migrations/2023090101-create-user.js
):
module.exports = {async up(queryInterface, Sequelize) {await queryInterface.createTable('users', {id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },username: { type: Sequelize.STRING(30), allowNull: false },created_at: { type: Sequelize.DATE, allowNull: false },updated_at: { type: Sequelize.DATE, allowNull: false }});await queryInterface.addIndex('users', ['username'], { unique: true });},async down(queryInterface) {await queryInterface.dropTable('users');}
};
2. 种子数据管理
创建种子文件(database/seeders/2023090101-demo-user.js
):
module.exports = {up: async queryInterface => {await queryInterface.bulkInsert('users', [{username: 'admin',created_at: new Date(),updated_at: new Date()}]);},down: async queryInterface => {await queryInterface.bulkDelete('users', { username: 'admin' });}
};
操作命令:
# 执行迁移
npx umzug up # 回滚迁移
npx umzug down# 运行种子
npx umzug seed
五、最佳实践建议
-
模型设计原则:
- 优先选择Snake Case命名(user_groups)
- 为常用查询字段添加索引
- 避免过度范式化设计
-
事务使用规范:
await ctx.model.transaction(async t => {await User.create({...}, { transaction: t });await Account.create({...}, { transaction: t }); });
-
缓存策略:
- 高频读取数据使用Redis缓存
- 缓存失效时间不超过5分钟
- 写操作同步更新缓存
总结
通过合理使用Sequelize ORM,开发者可以:
- 用面向对象的方式操作数据库
- 保持代码的可维护性和扩展性
- 实现高效的复杂查询
- 保证数据操作的原子性和一致性
正确实施数据库迁移方案,能够有效管理数据库结构变更,配合种子数据机制,显著提升开发测试效率。下一篇文章我们将探讨《RESTful API设计与安全防护》,解析如何构建安全高效的API系统。欢迎在评论区留下你遇见的「数据库操作与ORM」设计经验与挑战,共同探讨最佳实践!