Self-paced

Explore our extensive collection of courses designed to help you master various subjects and skills. Whether you're a beginner or an advanced learner, there's something here for everyone.

Bootcamp

Learn live

Join us for our free workshops, webinars, and other events to learn more about our programs and get started on your journey to becoming a developer.

Upcoming live events

Learning library

For all the self-taught geeks out there, here is our content library with most of the learning materials we have produced throughout the years.

It makes sense to start learning by reading and watching videos about fundamentals and how things work.

Search from all Lessons


LoginGet Started
← Back to Lessons
  • node

  • postgres

  • express

  • restapi

Edit on Github

CRUD data on Express

  • createQueryBuilder - Creates a query builder used to build SQL queries.
1const users = await repository 2 .createQueryBuilder("user") 3 .where("user.name = :name", { name: "John" }) 4 .getMany();
  • hasId - Checks if the given entity's primary column property is defined.
1 if (repository.hasId(user)) { 2 // ... do something 3 }
  • getId - Gets the primary column property values of the given entity. If entity has composite primary keys, then the returned value will be an object with names and values of primary columns.
1const userId = repository.getId(user); // userId === 1
  • create - Creates a new instance of User. Optionally accepts an object literal with user properties which will be written into newly created user object
1const user = repository.create(); // same as const user = new User(); 2const user = repository.create({ 3 id: 1, 4 firstName: "Timber", 5 lastName: "Saw" 6}); // same as const user = new User(); user.firstName = "Timber"; user.lastName = "Saw";
  • merge - Merges multiple entities into a single entity.
1const user = new User(); 2repository.merge(user, { firstName: "Timber" }, { lastName: "Saw" }); // same as user.firstName = "Timber"; user.lastName = "Saw";
  • preload - Creates a new entity from the given plain JavaScript object. If the entity already exists in the database, then it loads it (and everything related to it), replaces all values with the new ones from the given object, and returns the new entity. The new entity is actually an entity loaded from the database with all properties replaced from the new object.

Note that given entity-like object must have an entity id / primary key to find entity by. Returns undefined if entity with given id was not found.

1const partialUser = { 2 id: 1, 3 firstName: "Rizzrak", 4 profile: { 5 id: 1 6 } 7}; 8const user = await repository.preload(partialUser); 9// user will contain all missing data from partialUser with partialUser property values: 10// { id: 1, firstName: "Rizzrak", lastName: "Saw", profile: { id: 1, ... } }
  • save - Saves a given entity or array of entities. If the entity already exists in the database, it is updated. If the entity does not exist in the database, it is inserted. It saves all given entities in a single transaction (in the case of entity, manager is not transactional). Also supports partial updating since all undefined properties are skipped. Returns the saved entity/entities.
1await repository.save(user); 2await repository.save([ 3 category1, 4 category2, 5 category3 6]);
  • remove - Removes a given entity or array of entities. It removes all given entities in a single transaction (in the case of entity, manager is not transactional). Returns the removed entity/entities.
1await repository.remove(user); 2await repository.remove([ 3 category1, 4 category2, 5 category3 6]);
  • insert - Inserts a new entity, or array of entities.
1await repository.insert({ 2 firstName: "Timber", 3 lastName: "Timber" 4}); 5 6 7await manager.insert(User, [{ 8 firstName: "Foo", 9 lastName: "Bar" 10}, { 11 firstName: "Rizz", 12 lastName: "Rak" 13}]);
  • update - Partially updates entity by a given update options or entity id.
1await repository.update({ firstName: "Timber" }, { firstName: "Rizzrak" }); 2// executes UPDATE user SET firstName = Rizzrak WHERE firstName = Timber 3 4await repository.update(1, { firstName: "Rizzrak" }); 5// executes UPDATE user SET firstName = Rizzrak WHERE id = 1
  • delete - Deletes entities by entity id, ids or given conditions:
1await repository.delete(1); 2await repository.delete([1, 2, 3]); 3await repository.delete({ firstName: "Timber" });
  • softDelete and restore - Soft deleting and restoring a row by id
1const repository = connection.getRepository(Entity); 2// Delete a entity 3await repository.softDelete(1); 4// And You can restore it using restore; 5await repository.restore(1);
  • softRemove and recover - This is alternative to softDelete and restore.
1// You can soft-delete them using softRemove 2const entities = await repository.find(); 3const entitiesAfterSoftRemove = await repository.softRemove(entities); 4 5// And You can recover them using recover; 6await repository.recover(entitiesAfterSoftRemove);
  • count - Counts entities that match given options. Useful for pagination.
1const count = await repository.count({ firstName: "Timber" });
  • increment - Increments some column by provided value of entities that match given options.
1await manager.increment(User, { firstName: "Timber" }, "age", 3);
  • decrement - Decrements some column by provided value that match given options.
1await manager.decrement(User, { firstName: "Timber" }, "age", 3);
  • find - Finds entities that match given options.
1const timbers = await repository.find({ firstName: "Timber" });
  • findAndCount - Finds entities that match given find options. Also counts all entities that match given conditions, but ignores pagination settings (skip and take options).
1const [timbers, timbersCount] = await repository.findAndCount({ firstName: "Timber" });
  • findByIds - Finds multiple entities by id.
1const users = await repository.findByIds([1, 2, 3]);
  • findOne - Finds first entity that matches some id or find options.
1const user = await repository.findOne(1); 2const timber = await repository.findOne({ firstName: "Timber" });
  • findOneOrFail - Finds the first entity that matches the same id or find options. Rejects the returned promise if nothing matches.
1const user = await repository.findOneOrFail(1); 2const timber = await repository.findOneOrFail({ firstName: "Timber" });
  • query - Executes a raw SQL query.
1const rawData = await repository.query(`SELECT * FROM USERS`);
  • clear - Clears all the data from the given table (truncates/drops it).
1await repository.clear();

Additional Options

Optional SaveOptions can be passed as parameter for save.

  • data - Additional data to be passed with persist method. This data can be used in subscribers then.
  • listeners: boolean - Indicates if listeners and subscribers are called for this operation. By default they are enabled, you can disable them by setting { listeners: false } in save/remove options.
  • transaction: boolean - By default transactions are enabled and all queries in persistence operation are wrapped into the transaction. You can disable this behavior by setting { transaction: false } in the persistence options.
  • chunk: number - Breaks save execution into multiple groups of chunks. For example, if you want to save 100.000 objects but you have issues with saving them, you can break them into 10 groups of 10.000 objects (by setting { chunk: 10000 }) and save each group separately. This option is needed to perform very big insertions when you have issues with underlying driver parameter number limitation.
  • reload: boolean - Flag to determine whether the entity that is being persisted should be reloaded during the persistence operation. It will work only on databases which do not support RETURNING / OUTPUT statement. Enabled by default.

Example:

1// users contains array of User Entities 2userRepository.save(users, {chunk: users.length / 1000});

Optional RemoveOptions can be passed as parameter for remove and delete.

  • data - Additional data to be passed with remove method. This data can be used in subscribers then.
  • listener: boolean - Indicates if listeners and subscribers are called for this operation. By default they are enabled, you can disable them by setting { listeners: false } in save/remove options.
  • transaction: boolean - By default transactions are enabled and all queries in persistence operation are wrapped into the transaction. You can disable this behavior by setting { transaction: false } in the persistence options.
  • chunk: number - Breaks save execution into multiple groups of chunks. For example, if you want to save 100.000 objects but you have issues saving them, you can break them into 10 groups of 10.000 objects, by setting { chunk: 10000 }, and save each group separately. This option is needed to perform very big insertions when you have issues with underlying driver parameter number limitation.

Example:

1// users contains array of User Entities 2userRepository.remove(users, {chunk: entities.length / 1000});