1、安装

Linux 版

Linux下安装mysql

Mac 版

2、使用 Sequelize

一般会有两个依赖: mysql2 驱动和 Sequelize ORM 框架

  1. const Sequelize = require("sequelize");
  2. const config = require("./config");
  3. // 第一步:建立 ORM 连接
  4. var sequelize = new Sequelize(
  5. config.database,
  6. config.username,
  7. config.password,
  8. {
  9. host: config.host,
  10. dialect: "mysql",
  11. pool: {
  12. max: 5,
  13. min: 0,
  14. idle: 30000
  15. }
  16. }
  17. );
  18. // 第二步:建立 Model
  19. var Pet = sequelize.define(
  20. "pet",
  21. {
  22. id: {
  23. type: Sequelize.STRING(50),
  24. primaryKey: true
  25. },
  26. name: Sequelize.STRING(100),
  27. gender: Sequelize.BOOLEAN,
  28. birth: Sequelize.STRING(10),
  29. createdAt: Sequelize.BIGINT,
  30. updatedAt: Sequelize.BIGINT,
  31. version: Sequelize.BIGINT
  32. },
  33. {
  34. timestamps: false
  35. }
  36. );
  37. var now = Date.now();
  38. // 第三步:利用 Model 创建实例
  39. Pet.create({
  40. id: "g-" + now,
  41. name: "Gaffey",
  42. gender: false,
  43. birth: "2007-07-07",
  44. createdAt: now,
  45. updatedAt: now,
  46. version: 0
  47. })
  48. .then(function(p) {
  49. console.log("created." + JSON.stringify(p));
  50. })
  51. .catch(function(err) {
  52. console.log("failed: " + err);
  53. });
  54. // 查询操作 findAll
  55. (async () => {
  56. var pets = await Pet.findAll({
  57. where: {
  58. name: "Gaffey"
  59. }
  60. });
  61. console.log(`find ${pets.length} pets:`);
  62. for (let p of pets) {
  63. console.log(JSON.stringify(p));
  64. }
  65. })();
  66. // 更新操作 save
  67. (async () => {
  68. var p = await queryFromSomewhere();
  69. p.gender = true;
  70. p.updatedAt = Date.now();
  71. p.version ++;
  72. await p.save();
  73. })();
  74. // 删除操作
  75. (async () => {
  76. var p = await queryFromSomewhere();
  77. await p.destroy();
  78. })()

使用Sequelize操作数据库的一般步骤就是:

1、首先,通过某个Model对象的findAll()方法获取实例;
2、如果要更新实例,先对实例属性赋新值,再调用save()方法;
3、如果要删除实例,直接调用destroy()方法。

注意findAll()方法可以接收where、order这些参数,这和将要生成的SQL语句是对应的。

3、使用 sequelize-cli

方便快速创建数据库

  1. npm i sequelize-cli -D
  2. npm i sequelize
  3. npm i mysql2

配置.sequelizerc,如果不配置的话,sequelize init 初始化的文件夹会出现在项目根目录下面,如果配置了.sequelizerc 就可以指定到相应的目录

  1. const path = require('path')
  2. module.exports = {
  3. 'config': path.resolve('./app','config.json'),
  4. 'migrations-path': path.resolve('./app','migrations'),
  5. 'models-path': path.resolve('./app','models'),
  6. 'seeders-path': path.resolve('./app','seeders'),
  7. }

在项目根目录下执行

  1. npx sequelize init
  • 创建 migrations(定义如何创建表)
  1. npx sequelize migration:create --name create-shops-table
  2. // xxxxxxxxx-create-shops-table.js
  3. module.exports = {
  4. up: (queryInterface, Sequelize) => queryInterface.createTable(
  5. 'shops',
  6. {
  7. id: {
  8. type: Sequelize.INTEGER,
  9. autoIncrement: true,
  10. primaryKey: true,
  11. },
  12. name: {
  13. type: Sequelize.STRING,
  14. allowNull: false,
  15. },
  16. thumb_url: Sequelize.STRING,
  17. created_at: Sequelize.DATE,
  18. updated_at: Sequelize.DATE,
  19. },
  20. ),
  21. down: queryInterface => queryInterface.dropTable('shops'),
  22. };
  • 追加字段
  1. npx sequelize migration:create --name add-columns-to-shops-table
  2. // add-columns-to-shops-table.js
  3. module.exports = {
  4. up: (queryInterface, Sequelize) => Promise.all([
  5. queryInterface.addColumn('shops', 'address', { type: Sequelize.STRING }),
  6. ]),
  7. down: queryInterface => Promise.all([
  8. queryInterface.removeColumn('shops', 'address'),
  9. ]),
  10. };
  • 执行 migrations(创建/撤销表)
  1. npx sequelize db:migrate
  • 创建seed(初始化数据)
  1. npx sequelize seed:create --name init-shops
  2. // seeders/xxxxxxxxx-init-shops.js
  3. const timestamps = {
  4. created_at: new Date(),
  5. updated_at: new Date(),
  6. };
  7. module.exports = {
  8. up: queryInterface => queryInterface.bulkInsert(
  9. 'shops',
  10. [
  11. { id: 1, name: '店铺1', thumb_url: '1.png', ...timestamps },
  12. { id: 2, name: '店铺2', thumb_url: '2.png', ...timestamps },
  13. { id: 3, name: '店铺3', thumb_url: '3.png', ...timestamps },
  14. { id: 4, name: '店铺4', thumb_url: '4.png', ...timestamps },
  15. ],
  16. {},
  17. ),
  18. down: (queryInterface, Sequelize) => {
  19. const { Op } = Sequelize;
  20. // 删除 shop 表 id 为 1,2,3,4 的记录
  21. return queryInterface.bulkDelete('shops', { id: { [Op.in]: [1, 2, 3, 4] } }, {});
  22. },
  23. };
  • 执行 seed
  1. npx sequelize db:seed:all // 使用所有 seed
  2. npx sequelize db:seed --seed xxxxxxxxx-init-shopsjs // 使用指定 seed
  • 创建model(与数据库表结构做对应)
  1. npx sequelize model:create --name shops --attributes "name:string"

该命令会同时创建 models/shops.js 和 migrations/ xxx-create-shops.js,所以上述的migration命令用的不多,并且xxx-create-shops.js 会自动增加三个字段 id , createdAt , updatedAt

  1. // models/shops.js
  2. module.exports = (sequelize, DataTypes) => sequelize.define(
  3. 'shops',
  4. {
  5. name: {
  6. type: DataTypes.STRING,
  7. allowNull: false,
  8. }
  9. },
  10. {
  11. tableName: 'shops',
  12. },
  13. );
  14. // migrations/xxx-create-shops.js
  15. 'use strict';
  16. module.exports = {
  17. up: (queryInterface, Sequelize) => {
  18. return queryInterface.createTable('shops', {
  19. id: {
  20. allowNull: false,
  21. autoIncrement: true,
  22. primaryKey: true,
  23. type: Sequelize.INTEGER
  24. },
  25. name: {
  26. type: Sequelize.STRING
  27. },
  28. createdAt: {
  29. allowNull: false,
  30. type: Sequelize.DATE
  31. },
  32. updatedAt: {
  33. allowNull: false,
  34. type: Sequelize.DATE
  35. }
  36. });
  37. },
  38. down: (queryInterface, Sequelize) => {
  39. return queryInterface.dropTable('shops');
  40. }
  41. };

参考