在 GraphQL 中使用特定字符串搜索特定结果

Search for particular results with a certain string in GraphQL

我想根据特定 restaurant/takeaway 的 foodType 是否是 "Chicken","Pizza" 等[=来搜索 getFoodType 到 return 结果22=]

像这样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
   }
 }

我基本上想 return 所有带有 "Chicken" 的结果作为 foodType。类似于 foodType: "Chicken".

首先需要在Resolver

中获取要查询的foodType的值
const resolvers = {
  Query: {
    getFoodType: (_, args) => {
      const { foodType } = args
      ...
    },
  },
}

然后查询的时候用foodType

Eatery.find({ foodType })

终于要return结果

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