繁体   English   中英

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

[英]NestJS + Mongoose + GraphQL : “populate” not working

感谢伟大的框架!

我使用 mongoose 和 GraphQL 并有以下问题:

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

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

参数模式

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

用户模式

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

论据.model

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

  @Field()
  readonly argument: string;

  @Field()
  readonly userId: string;

  @Field()
  readonly username: string;
}

用户.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[];
}

用户服务

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的方式。 正如它在这里提到的,你试过这个吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM