Sequelize操作数据库(包括模型,增,删改)
Posted 嘴巴嘟嘟
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sequelize操作数据库(包括模型,增,删改)相关的知识,希望对你有一定的参考价值。
// Using NPM
$ npm install --save sequelize
// 使用哪种数据库选择不同的安装
$ npm install --save mysql2
连接数据库的配置
1、dbUrl.js
const dbUrl =
host: 'localhost',
user: 'root',
password: 'root',
database: 'realworld',
dialect: 'mysql'
module.exports = dbUrl
const Sequelize = require('sequelize');
const dbUrl = require('../config/config.default')
// database数据库名称 name 用户 password密码
const sequelize = new Sequelize(
dbUrl.database,
dbUrl.user,
dbUrl.password,
host: dbUrl.host, //数据库域名
dialect:dbUrl.dialect,
// 设置时区
timezon: '+08:00',
define:
timestamps: false //为模型添加 createdAt 和 updatedAt 两个时间戳字段(true or false)
,
pool:
max: 5,
min: 0,
idle: 10000
);
sequelize
.authenticate()
.then(() =>
console.log('Connection has been established successfully.');
)
.catch(err =>
console.error('Unable to connect to the database:', err);
);
module.exports = sequelize
运行项目 显示连接成功
定义mode
const users = db.define('t_user'/*自定义表名*/,
id:
type: Sequelize.INTEGER,
primaryKey: true, //主键
autoIncrement: true, //自增
comment: "自增id" //注释:只在代码中有效
,
//用户名
username:
type: Sequelize.STRING,
validate:
isEmail: true, //类型检测,是否是邮箱格式
,
//密码
pwd:
type: Sequelize.STRING(10),
allowNull: false,//不允许为null
,
//状态
status:
type: Sequelize.INTEGER,
defaultValue: 0,//默认值是0
,
//昵称
nickname:
type: Sequelize.STRING
,
//token
token:
type: Sequelize.UUID
,
create_time:
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
,
//使用自定义表名
freezeTableName: true,
//去掉默认的添加时间和更新时间
timestamps: false,
indexes:[
//普通索引,默认BTREE
unique: true,
fields: ['pid']
,
]
);
//同步:没有就新建,有就不变
// users.sync();
//先删除后同步
users.sync(
force: true
);
单表的增删改
增
let user = UsersModel.build(
username: "swnd",
password: "q11111"
);
user = await user.save();
console.log(user.get('id': 3));
改
const hasUser = await UsersModel.findOne(
where:
id: 6,
username: 'zhangsan'
);
hasUser.username = 'wanggangdan'
hasUser.save();
删
const hasUser = await UsersModel.findOne(
where:
id: 3
);
await hasUser.destroy();
以上是关于Sequelize操作数据库(包括模型,增,删改)的主要内容,如果未能解决你的问题,请参考以下文章