问题
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