前言
SQLite 是一种嵌入式数据库,它的数据库就是一个文件。
Sequelize 是一个基于 promise 的 Node.js ORM, 目前支持 Postgres, MySQL, MariaDB, SQLite 以及 Microsoft SQL Server. 它具有强大的事务支持, 关联关系, 预读和延迟加载,读取复制等功能.
基于 Sqlite3 的项目,直接是用 Sequelize 进行对象和表的映射。
环境配置
| 12
 
 | // 安装npm i sequelize sqlite3 -S
 
 | 
项目结构

配置文件夹 config
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | const path = require('path')
 const sqlite3 = require('sqlite3').verbose()
 module.exports = {
 test: {
 storage: path.join(__dirname, '../db/db_test.sqlite'),
 host: 'localhost',
 dialect: 'sqlite',
 dialectModule: sqlite3
 logging: console.log,
 }
 }
 
 | 
注意:sqlite 可以忽略密码。(PS:使用密码可能会无法创建 sqlite 文件)
在 window 中需要手动引入 sqlite3 否则会找不到。
模型文件夹 models
该文件夹中 index.js 入口文件,链接数据库。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 
 | const fs = require('fs')
 const path = require('path')
 const basename = path.basename(__filename)
 const Sequelize = require('sequelize')
 const config = require('../config/config')
 const sequelize = new Sequelize(undefined, undefined, undefined, config.test)
 
 const db = {}
 
 fs.readdirSync(__dirname)
 
 .filter(file => (file.indexOf('.' !== 0) && (file !== basename) && (file.slice(-3) === '.js')))
 .forEach(file => {
 
 
 const model = sequelize.import(path.join(__dirname, file))
 db[model.name] = model
 })
 
 Object.keys(db).forEach(modelName => {
 if (db[modelName].associate) {
 db[modelName].associate(db)
 }
 })
 
 db.sequelize = sequelize
 db.Sequelize = Sequelize
 module.exports = db
 
 | 
模型文件 User
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 
 | module.exports = (sequelize, DataTypes) => {
 
 
 
 const User = sequelize.define('user', {
 name: {
 type: DataTypes.STRING,
 allowNull: false
 },
 age: {
 type: DataTypes.INTEGER,
 defaultValue: 0
 },
 gender: {
 type: DataTypes.ENUM,
 values: ['男', '女', '未知'],
 defaultValue: '未知'
 }
 }, {
 tableName: 'user'
 })
 User.associate = models => {
 
 }
 return User
 }
 
 | 
参考:其他配置:options
知识点
分页查询
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 
 | class UserCtl {
 
 
 
 
 async index(ctx) {
 
 
 const { page = 1, pageSize = 10 } = ctx.request.body
 
 let offset = (page - 1) * pageSize
 try {
 const {count, rows} = await db.user.findAndCountAll({
 limit: parseInt(pageSize),
 offset: offset,
 })
 const data = {
 code: 0,
 msg: 'success',
 totalCount: count,
 data: rows,
 }
 ctx.ok(data)
 } catch (error) {
 const data = {
 code: 1,
 msg: '服务错误~',
 err: error.name
 }
 ctx.badRequest(data)
 }
 }
 }
 
 | 
API文档:findAndCountAll
findAndCountAll 和 findAll 区别。返回结果不同:前者返回 Promise<{count: number, rows: Model[]}>,count 对象总数,rows本次查到的对象数组。后者直接返回对象数组。
有人遇到个错误:分页总数计算错误问题 (PS:暂时还没有遇到)
参考
Sequelize API
Sequelize中文文档