- Install related modules
- npm install sequelize
- npm install pg
- 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); }); - 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 });
- Sync model to database
Account.sync({force: true }); // force: true will delete the existing table and rebuild the table according to the model
- 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); });
(1) sequelize postgres connection
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=325854708&siteId=291194637
Recommended
Ranking