Search code examples
node.jstypescriptmongoosegraphqltypegraphql

TypeGraphQL Field Resolver with mongoose relationship


I have trouble dealing with populating the field using TypeGraphQL.

Situation summary with an example:

TypeGraphQL

TypeDef

@ObjectType()
class User {
  ...
}

@ObjectType()
class Post {
  ...

  @Field()
  user: User
}

Resolver

import { Post, User } from '@/models' // mongoose schema 

@Resolver(() => Post)
class PostResolver {
  @Query(() =>. Post)
  async getPost(id: string) {
    return await Post.findById(id);
  }

  ...
  
  @FieldReoslver(() => User) 
  async user(@Root() post: Post) {
    return await User.findById(post.user) // Error Occurs here.
  }
}

Mongoose

PostSchema

const PostSchema = new Schema({
  ...

  user: {
    type: Schema.ObjectId,
    ref: "User",
  }
})

I want to populate user field when the data Post is requested, with the field User type.
So, I used @FieldResolverlike above, but I encountered the Type Error because post.user is a type of User, not ObjectId of mongoose.

The user field is a type of ObjectId first when the getPost resolver was executed, but I want to populate this field to User when the client gets the response.

How can I get through this?

Thanks in advance.


Solution

  • This is an old post, so maybe you have an answer already. Or maybe this could help someone else.

    In your TypeGraphQL typeDef, user would need to be of type string. It could not be of type "User".

    Also the name of your FieldResolver would need be different than user. However, that would not be follow normal patterns.

    So Perhaps in your typeDef change the post.user to post.userId instead. Then the FieldResolver would return a type of "User" for post.user allowing you to use readable GraphQL queries.

    post.user._id should then work.