【问题标题】:NestJS populate only populates first elementNestJS 填充仅填充第一个元素
【发布时间】:2021-05-05 14:37:49
【问题描述】:

我在 NestJS 中有一个 Mongoose 架构,如下所示:


...
@Prop()
  casinoAmount: number;

  @Prop()
  gameHyperLink: string;

  @Prop()
  casinoHyperLink: string;

  @Prop({ type: Types.ObjectId, ref: 'Game' })
  games: Game[];
}

我想进行一个查询,即进行完整的“左连接”。基本上是一个查询,它选择每个 Provider 以及相应游戏中的所有元素。

如果我进行常规查询(没有populate),它将简单地返回所有ObjectID's

    const providers = await this.providerRepository
      .find({})
      .skip(offset)
      .limit(limit)
      .exec();

但是当我像这样填充时

    
const providers = await this.providerRepository
      .find({})
      .populate('games')
      .skip(offset)
      .limit(limit)
      .exec();

但是,它只返回一个 game 对象,而不是所有对象的列表。

有人知道为什么会这样吗?

【问题讨论】:

    标签: node.js typescript express mongoose nestjs


    【解决方案1】:

    首先,当您使用 await 进行查询时,不要使用 exec(),并像这样在填充中使用 skip() 和 limit() 作为选项:

    await this.providerRepository.find({}).populate({
        path:'games',
        options: {
            limit: limit,
            skip: skip
    
        })
    

    【讨论】:

    • 感谢您的回答。该代码无法正常工作我尝试使用此查询并且它工作const provider = await this.providerModel .findOne({}) .populate('games', null, Game.name);
    • 但是如果您在填充后使用跳过和限制,它总是返回第一项,对于您的查询,使用跳过和限制,它是否正常工作?
    猜你喜欢
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多