Search code examples
mongodbexpressmongoosegraphqlexpress-graphql

Graphql create relations between two queries.Error cannot access before initialization


I have this code:

const ProductType = new GraphQLObjectType({
    name: 'Product',
    fields: {
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        category: {
            type: CategoryType,
            resolve: async (parent) => {
                return await Category.findOne({_id: parent.category});
            }
        }
    }
});

const CategoryType = new GraphQLObjectType({
    name: 'Category',
    fields: {
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        products: {
            type: ProductType,
            resolve: async (parent, args) => {
                return await Product.find({category: parent._id});
            }
        }
    }
});

const Query = new GraphQLObjectType({
    name: 'Query',
    fields: {
        Categories: {
            type: new GraphQLList(CategoryType),
            resolve: async () => {
                return await Category.find();
            }
        }
    }
});

When i try to compile i get ReferenceError: Cannot access 'CategoryType' before initialization. I understand that first of all I should declare and only after that use, but I saw a similar code in one lesson on YouTube, and I think that it should work, but it’s not.


Solution

  • fields can take a function instead of an object. This way the code inside the function won't be evaluated immediately:

    fields: () => ({
      id: { type: GraphQLID },
      name: { type: GraphQLString },
      category: {
        type: CategoryType,
        resolve: (parent) => Category.findOne({_id: parent.category}),
      }
    })