How to Use Sequelize in Node.js: Simple Guide
To use
Sequelize in Node.js, first install it with a database driver, then create a Sequelize instance to connect to your database. Define models to represent tables, and use Sequelize methods to query or update data asynchronously.Syntax
Sequelize uses a simple pattern: create a Sequelize instance with database details, define models with sequelize.define(), and perform operations like findAll() or create().
Each model represents a table, and fields define columns. Sequelize methods return promises, so use async/await to handle results.
javascript
import { Sequelize, DataTypes } from 'sequelize'; // Create connection const sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: 'mysql' // or 'postgres', 'sqlite', etc. }); // Define a model const User = sequelize.define('User', { username: { type: DataTypes.STRING, allowNull: false }, birthday: { type: DataTypes.DATE } }); // Use model methods async function example() { await sequelize.sync(); // create tables if not exist const user = await User.create({ username: 'jane', birthday: new Date(1990, 6, 20) }); const users = await User.findAll(); console.log(users); }
Example
This example shows how to connect to a SQLite database, define a Task model, add a task, and fetch all tasks.
javascript
import { Sequelize, DataTypes } from 'sequelize'; // Connect to SQLite database in memory const sequelize = new Sequelize('sqlite::memory:'); // Define Task model const Task = sequelize.define('Task', { title: { type: DataTypes.STRING, allowNull: false }, done: { type: DataTypes.BOOLEAN, defaultValue: false } }); async function run() { await sequelize.sync(); // create tables // Create a new task await Task.create({ title: 'Learn Sequelize' }); // Fetch all tasks const tasks = await Task.findAll(); tasks.forEach(task => { console.log(`Task: ${task.title}, Done: ${task.done}`); }); } run();
Output
Task: Learn Sequelize, Done: false
Common Pitfalls
- Not awaiting
sequelize.sync()before querying can cause errors because tables may not exist yet. - Forgetting to handle asynchronous calls with
async/awaitor.then()leads to unexpected results. - Using wrong dialect or missing database driver causes connection failures.
- Not defining
allowNullproperly can cause validation errors.
javascript
/* Wrong: Missing await on sync */ sequelize.sync(); User.create({ username: 'bob' }); // May fail if table not ready /* Right: Await sync before queries */ await sequelize.sync(); await User.create({ username: 'bob' });
Quick Reference
Here is a quick summary of common Sequelize methods:
| Method | Description |
|---|---|
| sequelize.define(name, attributes) | Define a new model (table) |
| sequelize.sync() | Create tables if they don't exist |
| Model.create(data) | Add a new record |
| Model.findAll() | Get all records |
| Model.findOne({ where }) | Get one record matching condition |
| Model.update(data, { where }) | Update records matching condition |
| Model.destroy({ where }) | Delete records matching condition |
Key Takeaways
Install Sequelize and a database driver before use.
Create a Sequelize instance with your database info.
Define models to represent tables and their columns.
Use async/await to handle Sequelize's asynchronous methods.
Always sync your models before querying the database.