NestJS + Mongoose + GraphQL:"populate" 不工作

NestJS + Mongoose + GraphQL : "populate" not working

感谢伟大的框架!

我将 Mongoose 与 GraphQL 结合使用,遇到以下问题:

如果我想解析存储在 populate 用户数组 "arguments" 中的 ObjectID,在 GraphQL 中,我会得到一个空参数数组作为答案的用户。

我怀疑定义引用 ArgumentSchema(MongoDB 模式的名称)或填充 arguments(用户属性的名称)时出错。这是如何正确工作的?

argument.schema

export const ArgumentSchema = new mongoose.Schema({
  argument: { type: String, required: true },
  userId: { type: String, required: true },
  username: { type: String, required: true },
});

user.schema

export const UserSchema = new mongoose.Schema({
  username: { type: String, required: true },
  email: { type: String, required: true },
  age: { type: Number, required: true },
  arguments: { type: [mongoose.Schema.Types.ObjectId], required: false, ref: 'ArgumentSchema' },
});

argument.model

@ObjectType()
export class ArgumentGQL {
  @Field(() => ID)
  readonly _id: string;

  @Field()
  readonly argument: string;

  @Field()
  readonly userId: string;

  @Field()
  readonly username: string;
}

user.model

@ObjectType()
export class UserGQL {
  @Field(() => ID)
  readonly _id: string;

  @Field()
  readonly username: string;

  @Field()
  readonly email: string;

  @Field()
  readonly age: number;

  @Field(() => [ArgumentGQL], { nullable: true })
  readonly arguments: ArgumentGQL[];
}

user.service

async getOne(id: string): Promise<UserGQL> {
    try {
      return await this.userModel.findById(id).populate('arguments').exec();
    } catch (e) {
      throw new BadRequestException(e);
    }
  }

GraphlQL 查询示例

query {
  getUser(id: "5dbcaf9f5ba1eb2de93a9301") {
      _id,
      username,
      email,
      age,
      arguments {
          argument,
          username
      }
  }
}

我想我还没有理解一些基本的东西...

如有任何帮助,我将不胜感激! 干杯

我猜问题出在你定义的方式上 user.schema。正如它提到的here,你试过这个吗?

{
 arguments: [{ type: [mongoose.Schema.Types.ObjectId], , ref: 'ArgumentSchema' }],
}