3

thanks for the great framework!

I use mongoose with GraphQL and have the following problem:

If I want to resolve the ObjectIDs stored in the array "arguments" of a user with populate, in GraphQL I get the user with an empty arguments array as answer.

I suspect the error when defining the reference ArgumentSchema (name of the MongoDB schema) or the populate arguments (name of the attributes of the user). How does this work correctly?

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 example

query {
  getUser(id: "5dbcaf9f5ba1eb2de93a9301") {
      _id,
      username,
      email,
      age,
      arguments {
          argument,
          username
      }
  }
}

I think I haven't understood something fundamental yet...

I would be grateful for any help! Cheers

1
  • I'm having the same problem do you have this project repository? Commented Jan 11, 2020 at 4:59

1 Answer 1

5

I guess the problem, maybe is the way you defined user.schema. As It mentioned here, have you tried this?

{
 arguments: [{ type: [mongoose.Schema.Types.ObjectId], , ref: 'ArgumentSchema' }],
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much Sir! You saved me hours ;)
@stoniemahonie You are welcome :) By the way, I use Typegoose and I think it's a bit cleaner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.