GraphQL error returning result of mongoose aggregate command

风流意气都作罢 提交于 2019-12-24 16:10:07

问题


This question is related to the answer posted here

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

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:

"The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned)."

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 ?


回答1:


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


来源:https://stackoverflow.com/questions/48208410/graphql-error-returning-result-of-mongoose-aggregate-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!