无法读取未定义的 属性 'orderBy'

Cannot read property 'orderBy' of undefined

我想按 adViews 的长度对数组进行排序。

但我收到以下错误:

TypeError: Cannot read property 'orderBy' of undefined

我该如何解决?

  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),
      },
    };
  }

从外观上看,Lodash 不使用默认导出。使用

import * as _ from 'lodash';

应该没问题。

您的 lodash 模块似乎未导入。 尝试只导入您需要的功能

import { orderBy } from 'lodash';