Skip to content

TypeError: Cannot read property 'databaseName' of undefined #4270

Closed

Description

@v1d3rm3

Issue type:
[x] bug report

Database system/driver:
[x] mssql

TypeORM version:
[x] latest

Steps to reproduce or a small repository showing the problem:

Here is a repo with the bug:
https://github.com/victorschinaider/typeorm-bug

I think pagination+ embedded orderBy+ subquery + leftJoinAndSelect combination is giving me the problem.

Activity

  1. vlapo commented on Jun 12, 2019

    @vlapo
    Contributor

    This should be fixed in @next branch. It is possible for you to use typeorm@next ?

  2. v1d3rm3 commented on Jun 12, 2019

    @v1d3rm3
    ContributorAuthor

    @next commits are far behind from master. @next will be 0.3.0?

  3. vlapo commented on Jun 12, 2019

    @vlapo
    Contributor

    Yes @next is branch for 0.3.0. This branch contains breaking changes not included in current master branch.

  4. v1d3rm3 commented on Jun 13, 2019

    @v1d3rm3
    ContributorAuthor

    We've a lot of code in 0.2.x. The lack of documentation of @next could be a problem too. =/

  5. tizzyapunkt commented on Oct 29, 2019

    @tizzyapunkt

    #747 might help. OrderBy expects propertyNames instead of column names.

  6. LoicMahieu commented on Dec 10, 2019

    @LoicMahieu

    I found a fix for the master branch, inspired by next:

    diff --git a/node_modules/typeorm/query-builder/SelectQueryBuilder.js b/node_modules/typeorm/query-builder/SelectQueryBuilder.js
    index cfd3ce2..113b128 100644
    --- a/node_modules/typeorm/query-builder/SelectQueryBuilder.js
    +++ b/node_modules/typeorm/query-builder/SelectQueryBuilder.js
    @@ -1458,15 +1458,17 @@ var SelectQueryBuilder = /** @class */ (function (_super) {
             });
         };
         SelectQueryBuilder.prototype.createOrderByCombinedWithSelectExpression = function (parentAlias) {
             var _this = this;
             // if table has a default order then apply it
             var orderBys = this.expressionMap.allOrderBys;
             var selectString = Object.keys(orderBys)
                 .map(function (orderCriteria) {
                 if (orderCriteria.indexOf(".") !== -1) {
    -                var _a = tslib_1.__read(orderCriteria.split("."), 2), aliasName = _a[0], propertyPath = _a[1];
    +                var _a = tslib_1.__read(orderCriteria.split("."), 3), aliasName = _a[0], propertyPath = _a.slice(1).join('.');
                     var alias = _this.expressionMap.findAliasByName(aliasName);
    -                var column = alias.metadata.findColumnWithPropertyName(propertyPath);
    +                var column = alias.metadata.findColumnWithPropertyPath(propertyPath);
                     return _this.escape(parentAlias) + "." + _this.escape(DriverUtils_1.DriverUtils.buildColumnAlias(_this.connection.driver, aliasName, column.databaseName));
                 }
                 else {
    @@ -1479,9 +1481,10 @@ var SelectQueryBuilder = /** @class */ (function (_super) {
             var orderByObject = {};
             Object.keys(orderBys).forEach(function (orderCriteria) {
                 if (orderCriteria.indexOf(".") !== -1) {
    -                var _a = tslib_1.__read(orderCriteria.split("."), 2), aliasName = _a[0], propertyPath = _a[1];
    +                var _a = tslib_1.__read(orderCriteria.split("."), 3), aliasName = _a[0], propertyPath = _a.slice(1).join('.');
                     var alias = _this.expressionMap.findAliasByName(aliasName);
    -                var column = alias.metadata.findColumnWithPropertyName(propertyPath);
    +                var column = alias.metadata.findColumnWithPropertyPath(propertyPath);
                     orderByObject[_this.escape(parentAlias) + "." + _this.escape(DriverUtils_1.DriverUtils.buildColumnAlias(_this.connection.driver, aliasName, column.databaseName))] = orderBys[orderCriteria];
                 }
                 else {

    God I beg your pardon 🤫

  7. highflying commented on Feb 11, 2020

    @highflying

    Any idea on when/how this will be fixed? I'm also trying to orderBy on a leftJoinAndSelect column.

  8. kwanso-nadeem commented on Mar 5, 2020

    @kwanso-nadeem

    Waiting for a fix here.

  9. sinclairnick commented on Apr 3, 2020

    @sinclairnick

    Not supporting pagination is a bit of a deal breaker tbh. I like Typeorm but lacking real pagination is a pretty big issue. Been trying to fix this for a while now, to no avail

  10. aayani commented on Apr 5, 2020

    @aayani

    Getting the same error while trying this combination with Postgres behind.

    Cannot read property 'databaseName' of undefined

    repository
    .createQueryBuilder('invite')
    .innerJoinAndSelect('invite.user', 'user')
    .where('invite.user_id = :userId', { userId })
    .orderBy('invite.updated_at', 'DESC', 'NULLS LAST')
    .orderBy('invite.created_at', 'DESC')
    .take(10)
    .skip((page - 1) * 10)
    .getMany();
    

    Can try raw query for now.

  11. btd1337 commented on Jun 26, 2020

    @btd1337

    Check if your query params are correct. Here my ordering query was with an incorrect property name in sort and then this error was reported.

    Fixing it, all works properly:

    Captura de tela de 2020-06-26 01-04-30

  12. AllanPinheiroDeLima commented on Aug 12, 2020

    @AllanPinheiroDeLima

    #747 might help. OrderBy expects propertyNames instead of column names.

    Is this in the docs ? I did'nt find this anywhere. I've lost good chunk of hours until I found your answer

    To explain why is this important:

    • I have a second database, not owned by me, which is updated by an automated software ( PACS - medical system ). I have mapped the properties that I use into a local model, so I can take advantage of typeorm, but when I used the query builder, since I changed the aliases of column names on my side, I was not able to order the query.
      If this was in docs, it would be great!

    I can make a pull request for this, since I'll forget by the end of the week anyways

    Now, my query is working as intended

  13. antowkabond commented on Oct 27, 2020

    @antowkabond

    I have the same issues.
    As for me, it helps

    @Entity({name: 'categories'})
    export class Category extends BaseEntity {
        @PrimaryGeneratedColumn()
        public id: number;
    
        @Column({name: 'my_name'})
        public name: string;
    }
    

    In QueryBuilder use qb.orderBy('categories.name', filter.orderDirection);
    Instead of column name from database. qb.orderBy('categories.my_name', filter.orderDirection);

  14. 21 remaining items

  15. alxestevam commented on Feb 23, 2023

    @alxestevam

    Same issue, but none of the above solutions worked for me. I am using a JSON field to order by:

    query.orderBy( 'call.data->>date', data.order);
    

    The call.data is the property name, so it should work.

    if I use the query from query.getQuery() in a PostgreSQL console the query works fine.

    @wladimirguerra I think this should work:

    query.addSelect('call.data->>date', 'callDataDate')
    .orderBy('callDataDate', data.order)
    
  16. andrey010 commented on Apr 25, 2023

    @andrey010
        const request = this.entityManager
          .createQueryBuilder(User, 'u')
          .where('u.user_uuid !=:user_uuid', { user_uuid: user.uuid })
          .innerJoinAndSelect('u.account', 'account', 'account.acco_uuid=:accountUuid', { accountUuid })
          .limit(take)
          .offset(skip)
    
        if (role) request.andWhere('u.role=:role', { role });
        if (by) request.orderBy(`u.${by}`, orderType === 'asc' ? 'ASC' : 'DESC');
        
        return request.getManyAndCount();
    

    Also had this error . My solution set take, skip to limit, offset

  17. RodriguesGabrielTi commented on Aug 14, 2023

    @RodriguesGabrielTi

    @andrey010 limit and offset can not work properly when used join on the same query:
    image

  18. fatahnuram commented on Sep 3, 2023

    @fatahnuram

    waiting for a fix here..

  19. pvogel1967 commented on Oct 27, 2023

    @pvogel1967

    Adding a further wrinkle here, if I want to order by a complex expression that does not correspond to a specific field, I also get this problem. Ex:

    qb.addOrderBy('CASE WHEN (EXTRACT(doy from now())::int-vds.doy) < 0 THEN 366+(EXTRACT(doy from now())::int-vds.doy) ELSE (EXTRACT(doy from now())::int-vds.doy) END', 'ASC');
    

    Where vds is a table (view, actually, but not important here) that I'm joining purely for the ability to sort.

  20. hitesh-pathak commented on Nov 17, 2023

    @hitesh-pathak

    #747 might help. OrderBy expects propertyNames instead of column names.

    Worked for me, thanks a ton!

  21. shaxi007 commented on Jan 31, 2024

    @shaxi007

    I think you are using getMany() method of typeorm. You shouldn't use like this orderBy('post.category_id'). You shuold use like this orderBy('post.category')

  22. dattran1232003 commented on Jul 27, 2025

    @dattran1232003

    #747 might help. OrderBy expects propertyNames instead of column names.

    Wow, 2025, and this is still correct, super!

  23. hungluu commented on Sep 13, 2025

    @hungluu

    Still happening in 0.3.26. I'm seriously thinking about migrating our bunch of NestJS apps out of typeorm by now. Too many weird issues and workarounds / small hacks applied throughout the years. 2k4 opened issues now and I don't often see the maintainers any where answering these issues these days. How should I not be concerned?

  24. RaederDev commented on Jan 12, 2026

    @RaederDev

    Still an issue also with postgresql. I had to add some ugly workarounds to bypass this. Is there a plan to fix this?

  25. gioboa commented on Jan 13, 2026

    @gioboa
    Collaborator

    Can you try the preview package of this PR please?

  26. RaederDev commented on Jan 13, 2026

    @RaederDev

    @gioboa thanks! I can confirm this patch fixes the issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions