灏天阁

Node/Koa2[30]: 数据建模

· Yin灏

目录结构

└─src
    └─db
        ├─model
        │  ├─index.js
        │  └─User.js
        ├─sync.js
        └─types.js

封装 sequelize 数据类型

src/db/types.js

const Sequelize = require("sequelize");
module.exports = {
  STRING: Sequelize.STRING,
  DECIMAL: Sequelize.DECIMAL,
  TEXT: Sequelize.TEXT,
  INTEGER: Sequelize.INTEGER,
  BOOLEAN: Sequelize.BOOLEAN,
};

处理数据建模

src/db/model/User.js

const { STRING, DECIMAL } = require("../types");

const User = seq.define("user", {
  userName: {
    type: STRING,
    allowNull: false,
    unique: true,
    comment: "用户名,唯一",
  },
  password: {
    type: STRING,
    allowNull: false,
    commit: "密码",
  },
  nickName: {
    type: STRING,
    allowNull: false,
    commit: "昵称",
  },
  gender: {
    type: DECIMAL,
    allowNull: false,
    defaultValue: 3,
    commit: "性别(1男,2女,3保密)",
  },
  picture: {
    type: STRING,
    commit: "头像,图片地址",
  },
  city: {
    type: STRING,
    commit: "城市",
  },
});
module.exports = User;

模型的入口文件

src/db/model/index.js

const User = require("./User");
module.exports = {
  User,
};

同步模型

src/db/sync.js

//...
require("./model/index");
//...

运行创建数据库命令

node src/db/sync.js

- Book Lists -