Skip to content

Instantly share code, notes, and snippets.

@LexVocoder
Last active June 16, 2026 00:10
Show Gist options
  • Select an option

  • Save LexVocoder/c4edba8a41f90eb0f124c33e30355836 to your computer and use it in GitHub Desktop.

Select an option

Save LexVocoder/c4edba8a41f90eb0f124c33e30355836 to your computer and use it in GitHub Desktop.
Sequelize syntax reference
// How to import from sequelize
const { Sequelize, DataTypes } = require('sequelize');
// How to instantiate a connection pool to sqlite
const sequelize = new Sequelize('sqlite::memory:', { logging: false });
// How to define a table
const Account = sequelize.define('Account', {
type: { type: DataTypes.ENUM('savings', 'checking'), allowNull: false },
name: { type: DataTypes.STRING, allowNull: false },
balance: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 },
});
// How to define a reciprocal relationship between two tables
Account.hasMany(Transaction, { foreignKey: 'accountId', as: 'transactions' });
Transaction.belongsTo(Account, { foreignKey: 'accountId', as: 'account' });
// How to run a fairly complex query. When not found, account is null.
const account = await Account.findByPk(req.params.account_id, {
include: [{ model: Transaction, as: 'transactions' }], // LEFT JOIN
order: [[{ model: Transaction, as: 'transactions' }, 'createdAt', 'DESC']],
});
// How to decrement an integer
await instance.decrement('balance', { by: amount });
// How to decrement an integer within a transaction
await instance.decrement('balance', { by: amount, transaction: t });
// How to start look-before-you-leap in a transaction
const instance = await Account.findByPk(fromAccountId, { transaction: t, lock: t.LOCK.UPDATE });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment