Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท Querying

CRUD Operations

Create, read, update and delete rows with TypeORM repositories and Sequelize models, understand save vs insert, upsert and bulk operations, and try the same flow in a runnable stand-in.

CRUD (create, read, update, delete) is most of what an application does with a database. Both ORMs cover it with a handful of methods; the differences are mostly in names and in how much the ORM does for you automatically.

Library code is read-only; the runnable blocks use a stand-in repository on node:sqlite with the same ideas.

Create

TypeScript
// TypeORM
const users = AppDataSource.getRepository(User);

const ana = users.create({ name: "Ana", email: "[email protected]" });
await users.save(ana);                          // INSERT, ana.id is now set

await users.insert({ name: "Bo", email: "[email protected]" });   // INSERT only, no entity returned
await users.save([{ name: "Cy" }, { name: "Di" }]);            // several rows
TypeScript
// Sequelize
const ana = await User.create({ name: "Ana", email: "[email protected]" });

const many = await User.bulkCreate([{ name: "Bo" }, { name: "Cy" }], { validate: true });
const [row, created] = await User.findOrCreate({ where: { email: "[email protected]" }, defaults: { name: "Ana" } });

TypeORM save() is upsert-like: with no id it inserts, with an existing id it first SELECTs and then UPDATEs only the changed fields. insert() skips that check and is faster for bulk loads. Sequelize's create always inserts; to update you call save() on an instance or update() on the model.

Read

TypeScript
// TypeORM
await users.find();                                   // all rows
await users.findOneBy({ id: 1 });                     // one or null
await users.findOneByOrFail({ id: 1 });               // throws EntityNotFoundError
await users.findAndCount({ take: 10 });               // [rows, total]
await users.count();
await users.exist({ where: { email: "[email protected]" } });
TypeScript
// Sequelize
await User.findAll();
await User.findByPk(1);                               // one or null
await User.findOne({ where: { email: "[email protected]" } });
await User.findAndCountAll({ limit: 10 });           // { count, rows }
await User.count();

Filtering gets its own lesson next. For now remember that a missing single row is null (or an exception if you used an OrFail method).

Update

TypeScript
// TypeORM: load, change, save (runs hooks, checks the row exists)
const ana = await users.findOneByOrFail({ id: 1 });
ana.name = "Ana Maria";
await users.save(ana);

// or a direct UPDATE (no entity loaded, no subscribers per entity)
await users.update({ id: 1 }, { name: "Ana Maria" });
await users.increment({ id: 1 }, "loginCount", 1);    // SET loginCount = loginCount + 1
TypeScript
// Sequelize
const ana = await User.findByPk(1);
ana!.name = "Ana Maria";
await ana!.save();                                    // only changed fields are written

await User.update({ name: "Ana Maria" }, { where: { id: 1 } });
await ana!.increment("loginCount", { by: 1 });

Prefer the atomic forms (increment, or SET x = x + 1) for counters. Load-modify-save loses updates when two requests run at the same time.

Delete

TypeScript
// TypeORM
await users.delete({ id: 1 });          // DELETE ... WHERE id = 1
await users.remove(ana);                // removes a loaded entity
await users.softDelete({ id: 1 });      // sets deletedAt
TypeScript
// Sequelize
await User.destroy({ where: { id: 1 } });
await ana.destroy();

Always pass a condition. In both libraries an empty where on destroy or update is either refused or removes everything, depending on the call and version, so never build one from user input without checking it is not empty.

The whole cycle, stand-in version

Node.js CRUD with a stand-in repository

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Lost updates: why increment is atomic

Two requests both read count = 5, both add one and both write 6. One increment vanished. The cure is to let the database do the arithmetic in one statement.

Node.js Lost update vs atomic update

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Later chapters add transactions and locking for cases where one statement is not enough.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does TypeORM repository.save(entity) do when the entity has no id?

    Without an id it inserts; with an existing id it updates the changed fields.
  2. 2. Which Sequelize call returns one row by primary key, or null?

    findByPk looks a row up by its primary key.
  3. 3. Why use increment() instead of read, add one, save?

    SET n = n + 1 is performed inside the database in a single statement.
  4. 4. What is the main difference between TypeORM insert() and save()?

    insert() is a plain, faster INSERT; save() decides between insert and update.

Summary

  • TypeORM: create builds, save inserts or updates, insert is a direct INSERT, find* reads, update, delete, softDelete change rows.
  • Sequelize: create, bulkCreate, findOrCreate, findAll, findByPk, update, destroy.
  • Single-row finders return null unless you use an OrFail variant.
  • Use atomic updates (increment) for counters.
  • Never run update or delete with an empty condition by accident.

Next: Filtering with Operators