PostgreSQL with Sequelize
Learn to work with PostgreSQL using Sequelize ORM for Node.js applications. This is a foundational concept in server-side JavaScript development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world Node.js experience. Take your time with each section and practice the examples
Introduction to PostgreSQL
PostgreSQL is a powerful, open-source relational database system. Sequelize is a promise-based Node.js ORM for PostgreSQL, MySQL, MariaDB, SQLite, and Microsoft SQL Server.. This is an essential concept that every Node.js developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Setting Up PostgreSQL with Sequelize
// Install dependencies
npm install sequelize pg pg-hstore
// Database configuration
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'postgres',
logging: false
});
// Test connection
async function testConnection() {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
testConnection();
// Define a Model
const { DataTypes } = require('sequelize');
const User = sequelize.define('User', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
age: {
type: DataTypes.INTEGER,
validate: {
min: 0,
max: 120
}
}
}, {
timestamps: true
});
// Sync the model with database
sequelize.sync({ force: true })
.then(() => {
console.log('Database synced');
})
.catch(err => {
console.error('Error syncing database:', err);
});