(一)sequelize postgres连接

  1. 安装相关模块
    • npm install sequelize
    • npm install pg
  2. 创建连接
    // 引用sequelize
    const Sequelize = require('sequelize');
    
    // 连接数据库方式一
    const sequelize = new Sequelize('testDb', 'postgres', '1', {
        host: 'localhost',
        dialect: 'postgres',
        operatorsAliases: false,
    
        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 1000
        }
    });
    
    // 连接数据库方式二
    // const sequelize = new Sequelize('postgres://postgres:1@localhost:5432/testDb');
    
    // 验证是否连接成功
    sequelize
        .authenticate()
        .then(() => {
            console.log('Connection has been established successfully');
        })
    .
    catch(err => { console.log('Unable to connect to the database:', err); });
  3. 创建模型
    const Account = sequelize.define('account', {
        id: {
            type: Sequelize.STRING(32),
            primaryKey: true
        },
        account: {
            type: Sequelize.STRING(20)
        },
        password: {
            type: Sequelize.STRING(20)
        }
    }, {
        timestamps: false,      // 默认创建createdAt和updatedAt字段,为false则不创建
        freezeTableName: true   // 默认创建表名为accounts,为true则为account
    });
  4. 同步模型到数据库
    Account.sync({force: true}); // force: true 将会删除现有表,根据模型重新建表
  5. 创建及查询
    Account.create({
        id: 'test',
        account: '4619',
        password: '4619'
    }).then(res => {
        // 返回创建对象的实例
    }, err => {
        console.log(err);
    });
    Account.findAll({
        raw: true
    }).then(rows => {
        // raw: true返回查询的表数据,默认为false返回查询实例
    }, err => {
        console.log(err);
    });
    sequelize文档 Getting started

猜你喜欢

转载自www.cnblogs.com/chenmengyuan/p/8993877.html