Search code examples
postgresqlnestjstypeorm

TypeORM postgresql order by enum text value


Trying to order by on an enum field (continent) by its text value on Postgresql. This works nice;

order by
    "Country"."continent"::TEXT DESC

Need to create the same result on TypeORM when I'm setting an orderBy;

orderBy = { ...orderBy, continent: value.sort };

How to to it in TypeOrm?


Solution

  • I know two ways to order by that property.

    The first one is using the regular way:

    const countries = await CountryEntity.find({
        order: {
            continent: "DESC"
        }
    })
    

    The other way (if you find useful the explicit conversion) is this:

    const orderBy: OrderByCondition = {
      continent: `CAST("Country"."continent" AS TEXT) ${value.sort}`,
    };
    
    const countries = await Country.find({
      order: orderBy,
    });