Application configuration of sequelize combined with mysql in node JS

1. Application configuration of sequelize combined with mysql in node JS

  1. By npm i sequelize mysql2 --savecommand to download sequelizeand mysql2.
  2. seq.js The code is as follows:
const Sequelize = require('sequelize')

const config = {
    
    
  // 端口号
  host: 'localhost',
  // 数据库名称
  dialect: 'mysql'
}

// 线上环境,使用连接池
config.pool = {
    
    
  max: 5, // 连接池中最大的连接数量
  min: 0, // 连接池中最小的连接数量
  idle: 10000 // 如果一个连接池 10s 之内没有被使用,则释放
}

const seq = new Sequelize('koa2_db', 'root', '123456', config)

module.exports = seq

// 测试连接
// seq.authenticate().then(() => {
    
    
//   console.log('ok')
// }).catch(() => {
    
    
//   console.log('err')
// })

  1. model.js The code is as follows:
const Sequelize = require('sequelize')
const seq = require('./seq')

// 创建 User 模型,数据表的名字是 users
const User = seq.define('user', {
    
    
  // id 会自动创建,并自动设置为主键,自增
  userName: {
    
    
    type: Sequelize.STRING, // varchar(255)
    allowNull: false
  },
  password: {
    
    
    type: Sequelize.STRING,
    allowNull: false
  },
  nickName: {
    
    
    type: Sequelize.STRING,
    comment: '昵称'
  }
  // 自动创建 createAt 和 update
})

// 创建 Blog 模型
const Blog = seq.define('blog', {
    
    
  title: {
    
    
    type: Sequelize.STRING,
    allowNull: false
  },
  content: {
    
    
    type: Sequelize.TEXT,
    allowNull: false
  },
  userId: {
    
    
    type: Sequelize.INTEGER,
    allowNull: false
  }
})


// 外键关联
// 先有 Blog,后有 User,由 Blog 发起查询
// 多对一
Blog.belongsTo(User, {
    
    
  // 创建外键  Blog.userId -> User.id
  foreignKey: 'userId'
})

// Blog.belongsTo(User)

// 先有 User,后有 Blog,由 User 发起查询
// 一对多
User.hasMany(Blog, {
    
    
  // 创建外键  Blog.userId -> User.id
  foreignKey: 'userId'
})

module.exports = {
    
    
  User,
  Blog
}

  1. sync.js The code is as follows:
const seq = require('./seq')

require('./model')

// 测试连接
seq.authenticate().then(() => {
    
    
  console.log('auth ok')
}).catch(() => {
    
    
  console.log('auth err')
})

// 执行同步
seq.sync({
    
     force: true}).then(() => {
    
    
  console.log('sync ok')
  process.exit()
})

Guess you like

Origin blog.csdn.net/weixin_42614080/article/details/111088332