gpt4 book ai didi

javascript - 忽略聚合管道中 $match 阶段的字段

转载 作者:行者123 更新时间:2023-11-30 19:54:54 24 4
gpt4 key购买 nike

我有一个 GraphQL 解析器,它接受 bool 类型的参数 test。在这个解析器中,我使用 Mongoose 执行 MongoDB 聚合,根据 test 参数的值从我的 users 集合返回文档。

这就是我的 GraphQL testUsers 解析器的样子:

Query: {
testUsers: async (root, args, context) => {
return await User.aggregate([
{
$match: {
test: args.test
}
}
])
}
}

在这里,args.test 可能是truefalseundefined。处理 truefalse 情况只是直接传递它的问题,但我想返回所有用户(不考虑 test 的值)如果 args.testundefined

有没有我可以在 $match 阶段为 test 传递的值,它不会考虑 test 字段?

最佳答案

你可以这样做

testUsers: async (root, args, context) => {
let match = { test: args.test }
if(typeof args.test === 'undefined') {
match = {}
}
return await User.aggregate([
{
$match: match
}
])
}

如果 args.test 未定义,您可以使用 let 变量并更改其值

关于javascript - 忽略聚合管道中 $match 阶段的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54097986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com