我想使用查询getFoodType
进行搜索,以根据特定餐厅/外卖店的foodType
是否为“Chicken”、“Pizza”返回结果
等等
像这样foodType:“鸡肉”
我尝试过使用参数和 mongoDB 过滤器(它是一个 MongoDB 服务器),但没有成功。
架构
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]
}
我的解析器
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
}
}
我本质上想返回所有以“Chicken”作为 foodType
的结果。类似于 foodType:“Chicken”
。
最佳答案
首先需要在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
}
},
},
}
关于javascript - 在 GraphQL 中搜索具有特定字符串的特定结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57236229/