GraphQL, как настроить запрос коллекции ссылок MongoDB, используя Nest js или type-graphql - PullRequest
0 голосов
/ 16 марта 2020

У меня есть вопрос о том, как использовать GraphQL для запроса коллекции ссылок в mongodb. У меня есть две коллекции: Люди и Кошка. У людей будет ноль или одна кошка, и Cat будет принадлежать одному Людям.

Сначала я использую graphql для создания Людей, затем копирую возвращенный Идентификатор Людей.

Затем я передаю, что Люди Идентификатор CreateCatService для создания кошки, так что эта созданная кошка принадлежит предыдущим созданным людям.

Теперь проблема в том, что я не могу запросить данные коллекции ref (вложенных).

mutation {
  createCat(
    input: {
      name: "my cat"
      age: 1
      breed: "test"
      people: "5e6edf120e27eb369db9ceaa" <----- People's id
    }
  ) {
    id
    name
    people {
      name <--- return null ???
    }
  }
}

Если я запрашиваю Cat, вложенный People будет нулевым, он показывает ошибку: "message": "ID cannot represent value: <Buffer 5e 6e df

{
  cats {
    name
    people {
      id
    }
  }
}

Ниже моя схема и код, генерирующий typedef.

export const PeopleSchema = new mongoose.Schema({
  name: String,
  cat: {type: mongoose.SchemaTypes.ObjectId, ref: "Cat"}
})
export const CatSchema = new mongoose.Schema({
  name: String,
  age: Number,
  breed: String,
  people: {type: mongoose.Schema.Types.ObjectId, ref: 'People'}
});
@ObjectType()
export class PeopleType {
  @Field(() => ID)
  id: string;

  @Field()
  name: string;

  @Field(type => CatType, { nullable: true })
  cat?: CatType
}
@ObjectType()
export class CatType {
  @Field(() => ID)
  id: string;

  @Field()
  readonly name: string;

  @Field(() => Int)
  readonly age: number;

  @Field()
  readonly breed: string;

  @Field(type => PeopleType, {nullable: true})
  readonly people?: PeopleType;
}

Мой CatInput:

@InputType()
export class CatInput {
  @Field()
  readonly name: string;

  @Field(() => Int)
  readonly age: number;

  @Field()
  readonly breed: string;

  @Field()
  readonly people: string; // this will be the people's id
}

Мой CreateCatService

  async create(createCatDto: CatInput): Promise<Cat> {
    const createdCat = new this.catModel(createCatDto);
    return await createdCat.save();

Мой CatResolver

  @Mutation(() => CatType)
  async createCat(@Args('input') input: CatInput) {
    return this.catsService.create(input);

Ответы [ 2 ]

0 голосов
/ 17 марта 2020

Попробовав много изменений, я обнаружил, что проблема в том, что я не заполнял подколлекцию. В CatResolver вместо возврата createdCat.save(); мне нужно сделать это:

    const savedCat = await createdCat.save();
    return await savedCat.populate('people').execPopulate();
0 голосов
/ 16 марта 2020

Я думаю, проблема в том, что ваш распознаватель не знает, как разрешить людей в ObjectType. Вам нужно создать FieldResolver в вашем классе Resolver.

См .: https://github.com/MichalLytek/type-graphql/blob/master/docs/resolvers.md#field -resolvers

В основном в вашем CatResolver вам нужен метод people типа FieldResolver , это должно ввести PeopleType (не уверен здесь: прочитайте статью)

  @FieldResolver()
  people(@Root() people: People) {
    // then using the people id in root, get the people detail from People.
  }
...