node JS 中 sequelize 结合 mysql 的应用配置

本文介绍如何使用Node.js和sequelize ORM框架集成MySQL数据库,包括安装配置、模型定义、关联关系设置及同步操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、node JS 中 sequelize 结合 mysql 的应用配置
  1. 通过 npm i sequelize mysql2 --save 命令下载 sequelizemysql2
  2. seq.js 代码如下所示:
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 代码如下所示:
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 代码如下所示:
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()
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值