【问题标题】:GraphQL query returning nullGraphQL 查询返回 null
【发布时间】:2019-06-14 11:31:40
【问题描述】:

我运行了这个成功的突变,它被保存到我的 MongoDB 数据库中:

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

但是,当我对其运行查询时:

query {
  getAllRecipes {
    _id
    name
    category
    likes
    createdDate
  }
}

我不清楚我为什么得到:

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

这是我的resolvers.js 文件:

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;
        }
    }
};

【问题讨论】:

    标签: express-graphql


    【解决方案1】:

    你有recipes吗?

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

    【讨论】:

    • 很好,如果我的回答对你有帮助,请不要羞于接受它
    • 哦,当然,我只需要等待所需的 2 分钟才能接受。
    猜你喜欢
    • 2020-01-07
    • 2020-01-15
    • 2021-01-15
    • 2020-03-01
    • 2023-03-05
    相关资源
    最近更新 更多