NestJS +猫鼬+ GraphQL:“填充”不起作用

问题描述 投票:0回答:1

感谢出色的框架!

我在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
      }
  }
}

我想我还不了解一些基本知识...

我将不胜感激!干杯

mongodb mongoose graphql nestjs mongoose-populate
1个回答
0
投票

我想这个问题,也许是您定义user.schema的方式。正如它提到的here,您尝试过吗?

{
 arguments: [{ type: [mongoose.Schema.Types.ObjectId], , ref: 'ArgumentSchema' }],
}
© www.soinside.com 2019 - 2024. All rights reserved.