Search code examples
express-graphql

GraphQL query returning null


I ran this successful mutation which was saved to my MongoDB database:

mutation {
  addRecipe(name: "Chole Dhania Masala", category: "Indian", description: "A tasty dish", instructions: "Cook it") {
    name
    category
    description
    instructions
  }
}

However, when I run a query for it:

query {
  getAllRecipes {
    _id
    name
    category
    likes
    createdDate
  }
}

I am not clear on why I got:

{
  "data": {
    "getAllRecipes": null
  }
}

This is my resolvers.js file:

exports.resolvers = {
    Query: {
        getAllRecipes: async (root, args, { Recipe }) => {
            const allRecipes = await Recipe.find();
            return allRecipes;
        }
    },
    Mutation: {
        addRecipe: async (root, { name, description, category, instructions, username }, { Recipe }) => {
            const newRecipe = await new Recipe({
                name,
                description,
                category,
                instructions,
                username
            }).save();
            return newRecipe;
        }
    }
};

Solution

  • Did you have any recipes?

    Query: {
        getAllRecipes: async (root, args, { Recipe }) => {
            const allRecipes = await Recipe.find();
            if (allRecipes) {
              return allRecipes;
            }
    
            return null;
        }
    }