我想使用查询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);
          });
      });
    },


阿波罗游乐场的当前查询

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


我本质上想返回所有带有“ Chicken”作为foodType的结果。类似于foodType: "Chicken"

最佳答案

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

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

09-19 13:44