sequelize-cli command. npm install sequelize sequelize-cli pg
npx sequelize-cli init
config/config.json file to match your database settings to complete the initialization process. npx sequelize-cli db:create
npx sequelize-cli seed:generate --name <descriptiveName>
npx sequelize-cli db:seed:all
npx sequelize-cli db:seed:undo
npx sequelize-cli db:seed:undo:all
npx sequelize-cli model:generate --name <ModelName> --attributes<column1>:<type>,<column2>:<type>,...
npx sequelize-cli db:migrate
npx sequelize-cli db:migrate:undo
npx sequelize-cli db:migrate:undo:all
const { Sequelize } = require('sequelize'); // Option 1: Passing a connection URI const sequelize = new Sequelize('sqlite::memory:') // Example for sqlite const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname') // Example for postgres // Option 2a: Passing parameters separately (sqlite) const sequelize = new Sequelize({ dialect: 'sqlite', storage: 'path/to/database.sqlite' }); // Option 2b: Passing parameters separately (other dialects) const sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */ });
try { await sequelize.authenticate(); console.log('Connection has been established successfully.'); } catch (error) { console.error('Unable to connect to the database:', error); }
sequelize.close()
up() methodreturn queryInterface.createTable(<TableName>, { <columnName>: { type: Sequelize.<type>, allowNull: <true|false>, unique: <true|false>, references: { model: { tableName: <TableName> } } } });
down() methodreturn queryInterface.dropTable(<TableName>);
await User.drop();
await sequelize.drop();
return queryInteface.addColumn(<TableName>, <columnName>: { type: Sequelize.<type>, allowNull: <true|false>, unique: <true|false>, references: { model: <TableName> }, });
return queryInterface.removeColumn(<TableName>, <columnName>);
instance.field // is the same as instance.get('field') // is the same as instance.getDataValue('field')
dataValues.getDataValue should only be used for custom getters.User) while tables have pluralized names (such as Users), although this is fully configurable.sequelize.define(modelName, attributes, options)init(attributes, options)sequelize.defineconst { Sequelize, DataTypes } = require('sequelize'); const sequelize = new Sequelize('sqlite::memory:'); const User = sequelize.define('User', { // Model attributes are defined here firstName: { type: DataTypes.STRING, allowNull: false }, lastName: { type: DataTypes.STRING // allowNull defaults to true } }, { // Other model options go here }); // `sequelize.define` also returns the model console.log(User === sequelize.models.User); // true
model.sync(options), an asynchronous function (that returns a Promise)| Function | Action |
|---|---|
User.sync() |
This creates the table if it doesn't exist (and does nothing if it already exists) |
User.sync({ force: true }) |
This creates the table, dropping it first if it already existed |
User.sync({ alter: true }) |
This checks what is the current state of the table in the database (which columns it has, what are their data types, etc), and then performs the necessary changes in the table to make it match the model. |
async/ awaitModel.create() method is a shorthand for building an unsaved instance with Model.build() and saving the instance with instance.save().// Create a new user const jane = await User.create({ firstName: "Jane", lastName: "Doe" }); console.log("Jane's auto-generated ID:", jane.id);
Model.bulkCreate method to allow creating multiple records at once, with only one query.Model.bulkCreate is very similar to Model.create, by receiving an array of objects instead of a single object.const create = await bulkCreate(records: Array, options: object): Promise<Array<Model>>
bulkCreate does not run validations on each object that is going to be created (which create does).
bulkCreate run these validations as well, you must pass the validate: true option. This will decrease performance.// Find all users const users = await User.findAll(); console.log(users.every(user => user instanceof User)); // true console.log("All users:", JSON.stringify(users, null, 2));
SELECT * FROM ...
Model.findAll({ attributes: ['foo', 'bar'] });
SELECT foo, bar FROM ...
Model.findAll({ attributes: ['foo', ['bar', 'baz'], 'qux'] });
SELECT foo, bar AS baz, qux FROM ...
Post.findAll({ where: { authorId: 2 } }); // SELECT * FROM post WHERE authorId = 2
// Change everyone without a last name to "Doe" await User.update({ lastName: "Doe" }, { where: { lastName: null } });
// Delete everyone named "Jane" await User.destroy({ where: { firstName: "Jane" } });
const remove = await bulkDelete(records: Array, options: object): Promise<Array<Model>>
order option takes an array of items to order the query by or a sequelize method.
[column, direction].ASC, DESC, NULLS FIRST, etc).Model.findAll({ order: [ // Will escape name and validate DESC | ASC against a list of valid direction parameters ['name', 'DESC' | 'ASC'] ] })
Model.findOne({ order: [ // will return `name` DESC or ASC ['name', `DESC` | `ASC`], // will return max('age') sequelize.fn('max', sequelize.col('age')), // will return max('age') DESC [sequelize.fn('max', sequelize.col('age')), 'DESC'], ] });
The elements of the order array can be the following:
raw field:
raw will be added verbatim without quotingraw is not set, the query will failSequelize.fn (which will generate a function call in SQL)Sequelize.col (which will quote the column name)limit and offset options allow you to work with limiting / pagination:// Fetch 10 instances/rows Project.findAll({ limit: 10 }); // Skip 8 instances/rows Project.findAll({ offset: 8 }); // Skip 5 instances and fetch the 5 after that Project.findAll({ offset: 5, limit: 5 });
ASC, DESC, NULLS FIRST, etc).Model.findAll({ group: 'name' }); // yields 'GROUP BY name'
| Action | Method |
|---|---|
| Add a new column to a table | async addColumn(table: string, key: string, attribute: object, options: object): Promise |
| Add a constraint to a table | async addConstraint(tableName: string, options: object): Promise |
| Add an index to a column | async addIndex(tableName: string \| object, attributes: Array, options: object, rawTablename: string): Promise |
| Delete multiple records from a table | async bulkDelete(tableName: string, where: object, options: object, model: Model): Promise |
| Insert multiple records into a table | async bulkInsert(tableName: string, records: Array, options: object, attributes: object): Promise |
| Update multiple records of a table | async bulkUpdate(tableName: string, values: object, identifier: object, options: object, attributes: object): Promise |
| Change a column definition | async changeColumn(tableName: string, attributeName: string, dataTypeOrOptions: object, options: object): * |
| Create a database | async createDatabase(database: string, options: object): Promise |
| Create an SQL function | async createFunction(functionName: string, params: Array, returnType: string, language: string, body: string, optionsArray: Array, options: object): Promise |
| Create a schema | async createSchema(schema: string, options: object): Promise |
| Create a table with given set of attributes | async createTable(tableName: string, attributes: object, options: object, model: Model): Promise |
| Describe a table structure | async describeTable(tableName: string, options: object): Promise<object> |
| Drop all schemas | async dropAllSchemas(options: object): Promise |
| Drop all tables from database | async dropAllTables(options: object): Promise |
| Drop a database | async dropDatabase(database: string, options: object): Promise |
| Drop an SQL function | async dropFunction(functionName: string, params: Array, options: object): Promise |
| Drop a schema | async dropSchema(schema: string, options: object): Promise |
| Drop a table from database | async dropTable(tableName: string, options: object): Promise |
| Get foreign key references details for the table | async getForeignKeyReferencesForTable(tableName: string, options: object): * |
| Returns all foreign key constraints of requested tables | async getForeignKeysForTables(tableNames: string[], options: object): Promise |
| Remove a column from a table | async removeColumn(tableName: string, attributeName: string, options: object): * |
| Remove a constraint from a table | async removeConstraint(tableName: string, constraintName: string, options: object): * |
| Remove an already existing index from a table | async removeIndex(tableName: string, indexNameOrAttributes: string \| string[], options: object): Promise |
| Rename a column | async renameColumn(tableName: string, attrNameBefore: string, attrNameAfter: string, options: object): Promise |
| Rename an SQL function | async renameFunction(oldFunctionName: string, params: Array, newFunctionName: string, options: object): Promise |
| Rename a table | async renameTable(before: string, after: string, options: object): Promise |
| Show all schemas | async showAllSchemas(options: object): Promise<Array> |
| Upsert | async upsert(tableName: string, insertValues: object, updateValues: object, where: object, options: object): Promise<boolean, ?number> |
count method simply counts the occurrences of elements in the database.console.log(`There are ${await Project.count()} projects`); const amount = await Project.count({ where: { id: { [Op.gt]: 25 } } }); console.log(`There are ${amount} projects with an id greater than 25`);
await User.max('age'); // 40 await User.max('age', { where: { age: { [Op.lt]: 20 } } }); // 10 await User.min('age'); // 5 await User.min('age', { where: { age: { [Op.gt]: 5 } } }); // 10 await User.sum('age'); // 55 await User.sum('age', { where: { age: { [Op.gt]: 5 } } }); // 50
END