mongodb - NestJS + Mongoose + GraphQL : "populate" not working

标签 mongodb mongoose graphql nestjs mongoose-populate

感谢伟大的框架!

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

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

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

参数.schema

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

参数.模型

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

  @Field()
  readonly argument: string;

  @Field()
  readonly userId: string;

  @Field()
  readonly username: string;
}

用户.模型

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

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

关于mongodb - NestJS + Mongoose + GraphQL : "populate" not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58666739/

相关文章:

mongodb - 当所有 $ 和条件匹配同一个子文档时匹配的 MongoDB find()?

node.js - 如何捕获 Mongoose 的错误代码

node.js - 使用 mongoose 更新 slug .pre ('save' )

mongodb - 如何在 Mongoose 中使用枚举验证字符串数组?

node.js - 我如何使用仅具有 Apollo Server 2 graphql 端点的快速中间件

node.js - MongoDB GET 请求不返回任何内容

node.js - 匹配 Mongoose 数组中指定的所有值

java - 使用 java 在 mongodb 上分页的最佳方法是什么

javascript - GraphQL 错误 "fields must be an object with field names as keys or a function which returns such an object."

amazon-web-services - 如何在 Appsync 中使用两个 API Key 分别授权两个 graphql 字段?