Sequelize
Sequelize is a modern TypeScript and Node.js ORM for Oracle, Postgres, MySQL, MariaDB, SQLite and SQL Server, and more. Featuring solid transaction support, relations, eager and lazy loading, read replication and more.
Define models
import { Sequelize, DataTypes } from 'sequelize';
const sequelize = new Sequelize('sqlite::memory:');
const User = sequelize.define('User', {
username: DataTypes.STRING,
birthday: DataTypes.DATE,
});
Persist and query
const jane = await User.create({
username: 'janedoe',
birthday: new Date(1980, 6, 20),
});
const users = await User.findAll();
Data Modeling
Define your models with ease and make optional use of automatic database synchronization.
const Wishlist = sequelize.define("Wishlist", {
title: DataTypes.STRING,
});
const Wish = sequelize.define("Wish", {
title: DataTypes.STRING,
quantity: DataTypes.NUMBER,
});
// Automatically create all tables
await sequelize.sync();
Associations
Define associations between models and let Sequelize handle the heavy lifting.
Wish.belongsTo(Wishlist);
Wishlist.hasMany(Wish);
const wishlist = await Wishlist.findOne();
const wishes = await wishlist.getWishes();
const wish = await wishlist.createWish({
title: 'Toys', quantity: 3,
});
await wishlist.removeWish(wish);
Soft deletion
Mark data as deleted instead of removing it once and for all from the database.
const User = sequelize.define("User",
{ username: DataTypes.STRING },
{ paranoid: true },
});
const user = await User.findOne();
await user.destroy();
await User.findAll(); // non-deleted only
await User.findAll({ paranoid: false }); // all