【问题标题】:NestJS + Mongoose + GraphQL : "populate" not workingNestJS + Mongoose + GraphQL:“填充”不起作用
【发布时间】:2020-02-28 04:39:37
【问题描述】:

感谢伟大的框架!

我在 GraphQL 中使用 mongoose,遇到以下问题:

如果我想使用 populate 解析存储在用户“参数”数组中的 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】:

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

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

【讨论】:

  • 非常感谢先生!你为我节省了几个小时;)
  • @stoniemahonie 不客气 :) 顺便说一句,我用的是Typegoose,我觉得它更干净一些。
猜你喜欢
  • 1970-01-01
  • 2021-07-22
  • 2015-05-09
  • 2019-06-20
  • 2023-01-15
  • 2020-05-21
  • 2017-05-15
  • 2021-12-20
  • 1970-01-01
相关资源
最近更新 更多