Home > Software design >  Cannot read property 'orderBy' of undefined
Cannot read property 'orderBy' of undefined

Time:01-04

I want to sort an array by the length of adViews.

But I get the following error:

TypeError: Cannot read property 'orderBy' of undefined

How do I fix it?

  import _ from 'lodash';

  async maxViewsQuery(page = 1, relations = []): Promise<PaginatedResult> {
    const take = 14;
    const [data, total] = await this.adRepository.findAndCount({
      where: `("Ad__adViews"."id" IS NOT NULL)`,
      take,
      skip: (page - 1) * take,
      relations,
    });

    const sort = _.orderBy(data, (view) => view.adViews.length);

    return {
      data: sort.map((ad: Ad) => ({
        id: ad.id,
        title: ad.title,
        adViews: ad.adViews.length,
      })),
      meta: {
        total,
        page,
        lastPage: Math.ceil(total / take),
      },
    };
  }

CodePudding user response:

Lodash doesn't use a default export, from the looks of it. Use

import * as _ from 'lodash';

and it should be fine.

CodePudding user response:

it seems your lodash module is not imported. try importing only the function you require

import { orderBy } from 'lodash';

  •  Tags:  
  • Related