(1) sequelize postgres connection

  1. Install related modules
    • npm install sequelize
    • npm install pg
  2. Create a connection
    // 引用sequelize
    const Sequelize = require('sequelize');
    
    // Connection to database mode one 
    const sequelize = new Sequelize('testDb', 'postgres', '1' , {
        host: 'localhost',
        dialect: 'postgres',
        operatorsAliases: false,
    
        pool: {
            max: 5,
            min: 0 ,
            acquire: 30000,
            idle: 1000
        }
    });
    
    // Connection to database method 2 
    // const sequelize = new Sequelize('postgres://postgres:1@localhost:5432/testDb');
    
    // Verify whether the connection is successful 
    sequelize
        .authenticate()
        .then(() => {
            console.log('Connection has been established successfully');
        })
    .
    catch(err => { console.log('Unable to connect to the database:', err); });

     

  3. Create a model
    const Account = sequelize.define('account', {
        id: {
            type: Sequelize.STRING(32),
            primaryKey: true
        },
        account: {
            type: Sequelize.STRING(20)
        },
        password: {
            type: Sequelize.STRING(20)
        }
    }, {
        timestamps: false ,       // The createdAt and updatedAt fields are created by default, if false , 
        freezeTableName: true    // The name of the created table is accounts by default, and if it is true, it is account 
    });

     

  4. Sync model to database
    Account.sync({force: true }); // force: true will delete the existing table and rebuild the table according to the model

     

  5. Create and query
    Account.create({
        id: 'test',
        account: '4619',
        password: '4619' 
    }).then(res => {
         // return the instance of the created object 
    }, err => {
        console.log(err);
    });
    Account.findAll({
        raw: true 
    }).then(rows => {
         // raw: true returns the query table data, the default is false and returns the query instance 
    }, err => {
        console.log(err);
    });
    sequelize文档 Getting started

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325854708&siteId=291194637