Search code examples
node.jstypeormquery-builder

Difference between .limit() and .take() in TypeORM


I am confused about different TypeORM methods with similar purposes. From TypeORM docs:

  • .take() — pagination limit. Sets maximal number of entities to take.
  • .skip() — pagination offset. Sets number of entities to skip.

I poorly understand what "pagination limit/offset" means. But, unfortunately, I couldn't find any information about distinguishing of, for instance, .take() and .limit(). I decided to see descriptions of these methods in TypeORM's source code:

  • .limit() — Set's LIMIT - maximum number of rows to be selected. NOTE that it may not work as you expect if you are using joins. If you want to implement pagination, and you are having join in your query, then use instead take method instead.
  • .offset() — Set's OFFSET - selection offset. NOTE that it may not work as you expect if you are using joins. If you want to implement pagination, and you are having join in your query, then use instead skip method instead.

Why these two methods cannot be used for pagination? What are their purposes then? Please, could anyone provide me with clear examples of using all these 4 methods? Thanks in advance.


Solution

  • The difference is that take and skip will be not part of the query you will execute, typeorm perform it after get results. This is util overall when your query include any kind of join because result is not like TypeORM map to us.

    On the other hand, limit and offset are included in the query, but may not work as you expect if you are using joins. For example, if you have an entity A with a relation OneToMany with B, and you try get the first three entries on A (using limit 3) and you do the join with B, if the first entry has 3 B, then you will get one A only.

    Take a look at the description that we can see if we use offset(same for limit)

    SelectQueryBuilder description