猫鼬聚合命令的GraphQL错误返回结果 [英] GraphQL error returning result of mongoose aggregate command
问题描述
此问题与在此处发布的答案有关
我需要从GraphQL查询返回聚合结果.这是查询代码:
I need to return an aggregation result from a GraphQL query. Here is the query code:
const companiesWithNoUsers = {
type: new GraphQLList(CompanyType),
resolve(root, args, context) {
return Company.aggregate([
{
$lookup: {
from: "users",
localField: "id",
foreignField: "company_id",
as: "company_users"
}
},
{
$match: {
"company_users:0": {
$exists: false
}
}
}
]).exec();
}
};
我在GraphQL上遇到以下错误:
I´m getting the follwing error at GraphQL:
Expected value of type \"Company\" but got: [object Object].
阅读文档后,我认为该错误与以下语句有关:
After reading the docs, I imagine the error is related to the following statement:
返回的文档是纯JavaScript对象,不是猫鼬文档(因为可以返回任何形状的文档)."
因此,我需要返回一个GraphQL CompanyType
.如何将返回值转换为GraphQL预期的格式?有针对此错误的另一种解决方案吗?
So, I need to return a GraphQL CompanyType
. How do I cast the return to the format expected to GraphQL ? Is there another solution for this error ?
推荐答案
您可以尝试将结果列表转换为Mongoose文档,然后将结果包装在Promise中,如下所示:
You could try casting the results list to Mongoose documents and wrap the result in a Promise as:
Company.aggregate(pipeline).exec((err, result) =>
(
new Promise((resolve, reject) => {
if (err) {
reject(err)
} else {
resolve(result.map(doc => {
delete doc.company_users;
return new Company( doc );
}))
}
})
))
这篇关于猫鼬聚合命令的GraphQL错误返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!