Sequelize
- Node.js course
- Advanced
- Lesson 35/83
- 5 min
Learn SQL with the Sequelize ORM.
What is Sequelize?
Sequelize is a popular ORM (Object-Relational Mapping) for Node.js. It supports PostgreSQL, MySQL, SQLite, and SQL Server. Instead of writing SQL you work with JavaScript classes (models).
Install: npm install sequelize sequelize pg. Connect: new Sequelize(uri). Define a model with sq.define("User", { name: DataTypes.STRING }). Sequelize generates the SQL behind the scenes; this gives less repetition and type safety. When you need raw SQL you can write it with sq.query().
Sequelize model definition
Defining a model in Sequelize: const User = sq.define("User", { name: DataTypes.STRING, age: DataTypes.INTEGER }). Each field takes a data type. Sequelize can auto-create the table: sq.sync().
Queries are also JavaScript-based: User.findAll({ where: { age: { [Op.gt]: 18 } } }). This produces SELECT * FROM Users WHERE age > 18. Transactions are supported via sq.transaction(). Sequelize can also model complex relations (one-to-many, many-to-many).
Practice Log the type of Sequelize
Import the Sequelize class from the sequelize module. Log typeof Sequelize.
Starter code
// import the module, get the class
// log its typeSample solution
const { Sequelize } = require("sequelize");
console.log(typeof Sequelize);Expected output
function
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the module name
const { Sequelize } = require("____")
const { Sequelize } = require("sequelize")
Explanation: The Sequelize module loads as 'sequelize'.
2 Match each piece to its role
| Term | Meaning |
|---|---|
Sequelize |
ORM |
sq.define |
Defines a model |
DataTypes.STRING |
Text type |
sq.sync |
Creates tables |
3 What does Sequelize provide?
- Network acceleration
- File compression
- ORM (SQL yerine nesne) Correct answer
- Cluster management
Explanation: Sequelize provides an ORM; you use objects instead of SQL.