Search code examples
node.jsnestjstypeorm

How to sort with typeorm?


The database contains the following data:

[
  {id: 1, username: "test", amount: 2},
  {id: 2, username: "example", amount: 0},
  {id: 3, username: "hello", amount: 1},
  {id: 4, username: "fsa", amount: 0},
  {id: 5, username: "aas", amount: 10},
]

now i need to query with typeorm to retrieve the data but i need to get it sorted according to amount field and with limit only 3 users, so i should get this:

 [
      {id: 5, username: "aas", amount: 10},
      {id: 1, username: "test", amount: 2},
      {id: 3, username: "hello", amount: 1},
    ]

how to make that query?


Solution

  • Using find method following solution works. Check out TypeORM's documentation for find options for more information and other options.

    userRepository.find({
            take: 3,
            order: {
                amount: "ASC" // "DESC"
            }
        }