【问题标题】:GraphQL error returning result of mongoose aggregate commandGraphQL错误返回mongoose聚合命令的结果
【发布时间】:2018-06-20 20:41:39
【问题描述】:

此问题与the answer posted here有关

我需要从 GraphQL 查询返回聚合结果。查询代码如下:

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 上遇到以下错误:

Expected value of type \"Company\" but got: [object Object].

阅读the docs后,我想错误与以下语句有关:

“返回的文档是纯 javascript 对象,而不是 mongoose 文档(因为可以返回任何形状的文档)。”

所以,我需要返回一个 GraphQL CompanyType。如何将返回转换为 GraphQL 预期的格式?这个错误有其他解决方案吗?

【问题讨论】:

    标签: mongodb mongoose aggregation-framework graphql graphql-js


    【解决方案1】:

    您可以尝试将结果列表转换为 Mongoose 文档并将结果包装在 Promise 中:

    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 );
                    }))
                }
            })
        ))
    

    【讨论】:

    • 不工作。 TypeError: _types.Company is not a constructor... 将对象转换为 GraphQLType 时出现问题Company...
    • 以上Company是Mongoose文档
    • 是的,我发现了。但仍然无法正常工作。同样的错误:"Expected value of type \"User\" but got: [object Object]."。我检查了输出,它是一组 Company mongoose 文档。不知道还缺少什么...实际上调用let company = new company(doc); console.log(Object.prototype.toString.call(company)) 我得到打印[object Object]....
    猜你喜欢
    • 2021-06-11
    • 2021-03-30
    • 1970-01-01
    • 2019-07-20
    • 2015-10-03
    • 2020-01-29
    • 2021-02-03
    • 2020-09-11
    • 2018-09-05
    相关资源
    最近更新 更多