Lesson 7 / 35
Setting Up Sequelize
Create a Sequelize instance, define a model with validation and understand its default table naming and timestamp behaviour.
By Rahul Agarwal · 15 years in web development
Instance, models, conventions
Sequelize starts with a Sequelize instance created from a connection URI or options, plus the matching driver package installed separately (pg for PostgreSQL, mysql2 for MySQL, sqlite3 for SQLite). You then define models with sequelize.define('User', attributes, options) or by extending Model and calling User.init(). Sequelize applies conventions you must know: the table name is the pluralised model name (User becomes Users) unless you set tableName or freezeTableName; every model gets createdAt and updatedAt columns unless timestamps: false; and if you do not declare a primary key, an id integer key is added. Attributes can carry validators such as isEmail that run in JavaScript before the query. These are convenient but they are not database constraints, so keep allowNull: false and unique as well. await sequelize.authenticate() checks that the connection works.
A model with validation
Uses an in-memory SQLite database so it can run locally after installing sequelize and sqlite3.
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:', { logging: false });
const User = sequelize.define('User', {
email: { type: DataTypes.STRING, allowNull: false, unique: true, validate: { isEmail: true } },
name: { type: DataTypes.STRING, allowNull: false },
});
async function main() {
await sequelize.authenticate();
await sequelize.sync(); // fine for a demo, use migrations in real apps
const asha = await User.create({ email: 'asha@example.com', name: 'Asha' });
console.log(asha.id, User.getTableName());
}
main();A hostel with house rules
Sequelize is like a hostel that assumes defaults unless told otherwise: rooms get plural names on the door, every entry gets a check-in and check-out time, and each resident gets a number. Convenient, but if your college uses different rules, you must say so up front in the model options.
Quick check: With default options, which table does sequelize.define('Order', ...) map to?
- order
- Orders
- tbl_order
- Order, exactly as written
Answer
Orders — Sequelize pluralises the model name by default. Set tableName or freezeTableName: true when you need a different table name.