Sequelize node连接数据库的ORM

Sequelize 中文文档
可以先看文档,文档很全,它的语句帮我们做了很多处理,而且很精简,让我们不用死记硬背sql语句,也不用去库里建表。

连接数据库

连接到数据库
要连接到数据库,必须创建一个 Sequelize 实例. 这可以通过将连接参数分别传递到 Sequelize 构造函数或通过传递一个连接 URI 来完成:

const { Sequelize } = require('sequelize');

// 方法 1: 传递一个连接 URI
const sequelize = new Sequelize('sqlite::memory:') // Sqlite 示例
const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname') // Postgres 示例

// 方法 2: 分别传递参数 (sqlite)
const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: 'path/to/database.sqlite'
});

// 方法 3: 分别传递参数 (其它数据库)
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: /* 选择 'mysql' | 'mariadb' | 'postgres' | 'mssql' 其一 */
});

定义模型 (定义表结构)

module.exports = function(sequelize, DataTypes) {
  return sequelize.define(
    'project',
    {
      id: {
        type: DataTypes.INTEGER(11),
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
      },
      name: { type: DataTypes.STRING(255), allowNull: true },
      title: { type: DataTypes.STRING(255), allowNull: true },
      report_fix_id: { type: DataTypes.STRING(1000), allowNull: true },
      fix_url: { type: DataTypes.STRING(2000), allowNull: true },
      ignore_key: {
        type: DataTypes.STRING(2000),
        allowNull: true,
        comment: '简化打印对象中比较大的对象'
      },
      env: {
        type: DataTypes.STRING(255),
        allowNull: true,
        comment: '哪些环境能上报日志'
      },
      report_interval: {
        type: DataTypes.INTEGER(11),
        allowNull: true,
        comment: '上报时间间隔'
      },
      ctime: {
        type: DataTypes.INTEGER(10),
        allowNull: true,
        get() {
          return moment
            .unix(this.getDataValue('ctime'))
            .format('YYYY/MM/DD HH:mm:ss')
        }
      },
      del: { type: DataTypes.INTEGER(1), allowNull: true, defaultValue: '0' }
    },
    {
      tableName: 'project'
    }
  )
}

模型同步 (真正从数据库创建)

定义模型时,你要告诉 Sequelize 有关数据库中表的一些信息. 但是,如果该表实际上不存在于数据库中怎么办? 如果存在,但具有不同的列,较少的列或任何其他差异,该怎么办?

这就是模型同步的来源.可以通过调用一个异步函数(返回一个Promise)model.sync(options). 通过此调用,Sequelize 将自动对数据库执行 SQL 查询. 请注意,这仅更改数据库中的表,而不更改 JavaScript 端的模型.

User.sync() - 如果表不存在,则创建该表(如果已经存在,则不执行任何操作)

User.sync({ force: true }) - 将创建表,如果表已经存在,则将其首先删除 (这个不要用,也最好别试)

User.sync({ alter: true }) - 这将检查数据库中表的当前状态(它具有哪些列,它们的数据类型等),然后在表中进行必要的更改以使其与模型匹配.

sequelize
  .authenticate()
  .then(() => {
    console.log('数据库连接成功'.green)
    // sequelize.sync({ alter: true })
  })
  .catch(err => {
    console.log('数据库连接失败'.red)
  })

创建实例(修改内容INSERT)

尽管模型是一个类,但是你不应直接使用 new 运算符来创建实例. 相反,应该使用 build 方法:

const jane = User.build({ name: "Jane" });
console.log(jane instanceof User); // true
console.log(jane.name); // "Jane"

但是,以上代码根本无法与数据库通信(请注意,它甚至不是异步的)! 这是因为 build 方法仅创建一个对象,该对象 表示 可以 映射到数据库的数据. 为了将这个实例真正保存(即持久保存)在数据库中,应使用 save 方法:

await jane.save();
console.log('Jane 已保存到数据库!');

请注意,从上面代码段中的 await 用法来看,save 是一种异步方法. 实际上,几乎每个 Sequelize 方法都是异步的. build 是极少数例外之一.

非常有用的捷径: create 方法
Sequelize提供了 create 方法,该方法将上述的 build 方法和 save 方法合并为一个方法:

const jane = await User.create({ name: "Jane" });
// Jane 现在存在于数据库中!
console.log(jane instanceof User); // true
console.log(jane.name); // "Jane"

简单 SELECT 查询

你可以使用 findAll 方法从数据库中读取整个表:

// 查询所有用户
const users = await User.findAll();
console.log(users.every(user => user instanceof User)); // true
console.log("All users:", JSON.stringify(users, null, 2));

相当于sql语句

SELECT * FROM ...

嗯,写一些建表与查询的流程,照着官网抄也没什么意思。使用这个我们可以很轻松的操作数据库,使我们写node接口的时候效率翻倍~