为什么要使用Sequelize?
- 平常系统中的增删改查、设置外键、连表查询等操作都比较繁琐,需要记忆SQL语句
- 需要手动执行和创建数据表
- 前端调用api直接操作数据库,缺乏安全性
ORM - Object Relational Mapping
- 通过对象关系的形式将数据映射到数据库
- 通过操作对象来操作数据库
- 可以规范数据结构
- 数据表,用JS中的模型(class或对象)代替
- 一条或多条记录,用JS中的一个对象或数组代替
- SQL语句,用对象方法代替
环境准备
安装sequelize及依赖的mysql2
npm i sequelize mysql2 -S
建模(外键)& 同步到数据库
1. 创建连接实例,并模块化
新建seq.js文件创建连接实例,后面我们会多次使用这个实例进行创建模型、同步数据等等,所以将此单独写成一个模块
const Sequelize = require('sequelize')//实例配置const conf = {host: 'localhost', // 主机名dialect: 'mysql' // 操作的数据库类型}// 创建实例const seq = new Sequelize('seq_test', 'root', 'mysqlroot', conf) // 数据库名 用户名 密码 配置module.exports = seq;
我们可以使用Sequelize中的如下方法测试连接是否成功
// 测试连接seq.authenticate().then(() => {console.log('ok');}).catch(() => {console.log('err');})
2. 创建所需的数据模型
新建model.js将抽象的数据模型用代码体现出来
const Sequelize = require('sequelize')const seq = require('./seq')// 创建 User 模型 数据表名users(与mongoose相似)const User = seq.define('user', {// id 会自动创建,并设为主键自增userName: {type: Sequelize.STRING, // varchar(255) 255个长度字符allowNull: false // 是否可为空},password: {type: Sequelize.STRING,allowNull: false},nickName: {type: Sequelize.STRING}// 自动创建 createdAt 和 updatedAt})const Blog = seq.define('blog', {title: {type: Sequelize.STRING,allowNull: false},content: {type: Sequelize.TEXT,allowNull: false},userId: {type: Sequelize.INTEGER,allowNull: false}})module.exports = {User,Blog}
我们也可以在代码中定义外键
// 创建外键关联Blog.belongsTo(User, { // 多对一// 创建外键 Blog.userId => User.idforeignKey: 'userId',onDelete: 'cascade'})User.hasMany(Blog, { // 一对多// 创建外键 Blog.userId => User.idforeignKey: 'userId'})
虽然只是一个博客id与用户id的关联,但是我们需要为这两个模型都创建关联,否则在后面的连表查询会找不到两个表的关系。onDelete属性是外键约束的类型,cascade是指从父表中删除或更新对应的行,同时自动的删除或更新自表中匹配的行。
3. 同步数据表结构
新建sync.js,将刚才定义好的模型同步到数据库中
const seq = require('./seq')require('./model') // 导入模型// 测试连接seq.authenticate().then(() => {console.log("auth ok");}).catch((err) => {console.log(err);})// 同步seq.sync({ force: true }).then(() => { // 强制同步console.log("sync ok");process.exit()})
增删改查 & 连表查询
1. 增加数据
由于对数据库的操作是I/O操作,所以几乎所有的代码都是异步代码,我们使用自执行的async函数将需要执行的代码包裹一下
const { User, Blog } = require('./model')!(async function () {// 创建用户const zhangsan = await User.create({userName: 'zhangsan',password: '123',nickName: '张三'})// insert into users (...) values (...)console.log('zhangsan', zhangsan.dataValues);const lisi = await User.create({userName: 'lisi',password: '123',nickName: '李四'})// 创建博客const blog1 = await Blog.create({title: '标题1',content: '内容1',userId: zhangsan.id})const blog2 = await Blog.create({title: '标题2',content: '内容2',userId: zhangsan.id})const blog3 = await Blog.create({title: '标题3',content: '内容3',userId: lisi.id})})()
2. 查询数据
查询一条记录```javascript const zhangsan = await User.findOne({ where: { // 条件
userName: 'zhangsan'
} }) console.log(“zhangsan”, zhangsan.dataValues); ```
查询特定的列```javascript const zhangsanName = await User.findOne({ attributes: [‘userName’, ‘nickName’], where: {
userName: 'zhangsan'
} }) console.log(zhangsanName.dataValues); ```
查询一个列表```javascript const zhangsanBlogList = await Blog.findAll({ where: {
userId: 1
}, order: [ // 排序
["id", 'desc']
] }) console.log(zhangsanBlogList.map(blog => blog.dataValues));
`` <br />这里的zhangsanBlogList是一个列表,所以会有很多的列数据,列中的datavalues才是我们想看到的数据,所以使用map`函数简单处理一下分页```javascript const blogPageList = await Blog.findAll({ limit: 2, // 限制本次查询 2 条 offset: 0, // 跳过多少条 order: [
["id", 'desc']
] }) console.log(blogPageList.map(blog => blog.dataValues)); ```
查询总数```javascript const blogListAndCount = await Blog.findAndCountAll({ limit: 2, offset: 0, order: [
["id", 'desc']
] }) console.log(blogListAndCount.count, blogListAndCount.rows.map(blog => blog.dataValues));
`` <br />查询总数时也可以分页,分页的数据存在rows`属性上- 连表查询```javascript
// 连表查询1
const blogListWithUser = await Blog.findAndCountAll({
order: [
], include: [['id', 'desc']
] }) // console.log(blogListWithUser.rows.map(blog => { // const blogVal = blog.dataValues // blogVal.user = blogVal.user.dataValues // return blogVal // })); // 连表查询2 const userListWithBlog = await User.findAndCountAll({ attributes: [‘userName’, ‘nickName’], include: [{model: User,attribites: ['userName', 'nickName'],where: {userName: 'zhangsan'}}
] }) console.log(JSON.stringify(userListWithBlog.rows.map(user => { const userVal = user.dataValues console.log(userVal); userVal.blogs = userVal.blogs.map(blog => blog.dataValues) return userVal })));{model: Blog}
<a name="3171f734"></a>#### 3. 更新数据```javascriptconst updateRes = await User.update({nickName: '张三1'},{where: {userName: 'zhangsan'}})console.log(updateRes[0] > 0);
updateRes是[1]这样的一个数组,里面的值是受影响了几行,我们可以根据这个判断更新成功与否4. 删除数据
// 删除一条博客const deleteBlogRes = await User.destroy({where: {id: 4}})console.log(deleteBlogRes);// 删除一个用户const deleteUserRes = await User.destroy({where: {id: 1}})console.log(deleteUserRes);
由于设置了外键,删除用户时,该用户所对应的博客也会跟着删除
连接池
在以上开发中,每一个用户进来都会和数据库创建一个连接,连接数多了会消耗很大的性能。所以在线上我们采用连接池的方式来做。连接池存在于内存中,他可以根据用户的连接数动态创建连接,等待用户的使用。每个用户进来都会使用连接池的连接与数据库关联,当连接数超过连接池的最大连接数的时候,下一个用户的连接会等待排队,当没有用户连接时,连接池中的连接会自动释放。
连接池的配置比较简单,就是在连接配置中加入pool属性,当项目处在线上添加上此配置即可
// 线上环境 使用连接池conf.pool = {max: 5, // 连接池中最大的连接数量 (根据实际用户访问量动态修改)min: 0, // 最小idle: 10000 // 如果一个连接池 10 s 之内没有被使用,则释放}
