【问题标题】:Search for particular results with a certain string in GraphQL在 GraphQL 中使用特定字符串搜索特定结果
【发布时间】:2019-12-05 18:06:16
【问题描述】:

我想使用我的查询 getFoodType 进行搜索,以根据特定餐厅/外卖店的 foodType 是否为 "Chicken","Pizza" 等返回结果

点赞foodType: "Chicken"

我尝试过使用参数和 mongoDB 过滤器(它是一个 MongoDB 服务器),但没有成功。

Schema

const EaterySchema = new Schema({
  name: {
    type: String,
    required: true
  },
  address: {
    type: String,
    required: true
  },
  foodType: {
    type: String,
    required: true
  }
});

我的架构类型

  type Eatery {
    id: String!
    name: String!
    address: String!
    foodType: String!
  }
  type Query {
    eatery(id: String!): Eatery
    eateries: [Eatery]
    getFoodType(foodType: String): [Eatery]
  }

我的Resolver

    getFoodType: () => {
      return new Promise((resolve, reject) => {
        Eatery.find({})
          .populate()
          .exec((err, res) => {
            err ? reject(err) : resolve(res);
          });
      });
    },

Apollo Playground 中的当前查询

{
   getFoodType (foodType: "Chicken") {
     id
     name
     address
     foodType
   }
 }

我基本上想以“鸡”作为foodType 返回所有结果。类似foodType: "Chicken"

【问题讨论】:

    标签: javascript reactjs typescript graphql apollo


    【解决方案1】:

    首先需要在Resolver中获取要查询的foodType的值

    const resolvers = {
      Query: {
        getFoodType: (_, args) => {
          const { foodType } = args
          ...
        },
      },
    }
    

    然后查询时使用foodType

    Eatery.find({ foodType })
    

    最后需要返回结果

    new Promise((resolve, reject) => {
      return Eatery.find({ foodType })
        .populate()
        .exec((err, res) => {
          err ? reject(err) : resolve(res)
        })
    })
    

    完整示例

    const resolvers = {
      Query: {
        getFoodType: (_, args) => {
          const { foodType } = args
          return new Promise((resolve, reject) => {
            return Eatery.find({ foodType })
              .populate()
              .exec((err, res) => {
                err ? reject(err) : resolve(res)
              })
          })
        },
      },
    }
    

    使用async/await

    const resolvers = {
      Query: {
        getFoodType: async (_, { foodType }) => {
          try {
            const eaterys = await Eatery.find({ foodType }).populate()
            return eaterys
          } catch (e) {
            // Handling errors
          }
        },
      },
    }
    

    【讨论】:

    • 效果很好@XYShaoKang 它正在返回所有带有该foodType 的餐馆,谢谢!只是出于兴趣,为什么要使用 GQL Mutation 而不是 Query
    • 这是我的错误,应该使用Query :sweat_smile:
    • 太棒了!另外,如果您有时间,我会将上面的 footType 更改为 foodType
    • 对不起,我的英语不是母语,所以我对错误的单词不是很敏感。我没有仔细检查它们。我已经纠正了他们?。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 2014-05-27
    • 2023-03-07
    • 2021-12-02
    • 1970-01-01
    相关资源
    最近更新 更多