Mongoose:调用另一个解析器中的解析器
我有订阅活动的用户:Mongoose:调用另一个解析器中的解析器,mongoose,graphql,graphql-js,Mongoose,Graphql,Graphql Js,我有订阅活动的用户: const EventType = new GraphQLObjectType({ name:'Event', fields:() => ({ id: {type:GraphQLID} }) }); const UserType = new GraphQLObjectType({ name:'User', fields:() => ({ id: {type:GraphQLStrin
const EventType = new GraphQLObjectType({
name:'Event',
fields:() => ({
id: {type:GraphQLID}
})
});
const UserType = new GraphQLObjectType({
name:'User',
fields:() => ({
id: {type:GraphQLString},
_subscriptionIds: { type: new GraphQLList(GraphQLID) },
subscriptions: {
type: new GraphQLList(EventType),
async resolve(parent, args) {
return Event.find( {_id: { $in: parent._subscriptionIds}})
}
}
anotherField: {
type: new AnotherType,
async resolve(parent, args) {
console.log(parent.subscriptions) // parent.subscriptions is undefined, I need to resolve it.
}
})
});
长话短说,我需要访问另一个字段解析程序中的parent.subscriptions(类型为Event)。有点像“强制调用”订阅解析程序
有可能吗?怎么可能
谢谢!:) 您通常不应该从一个解析器调用另一个解析器。如果您有两个或多个解析器共有的代码,您可以将该代码提取到它自己的函数(可能是一个单独的模块)中,然后从两个解析器调用它 因此,您的代码可以如下所示:
subscriptions: {
type: new GraphQLList(EventType),
async resolve(parent, args) {
return getSubscriptionsByIds(parent._subscriptionIds)
},
},
anotherField: {
type: new AnotherType,
async resolve(parent, args) {
const subscriptions = await getSubscriptionsByIds(parent._subscriptionIds)
// do something else with the subscriptions here
},
},
但是,这将导致对数据库的额外调用,除非您已经使用DataLoader来批处理这样的调用。更好的解决方案是将订阅获取逻辑向上移动一个级别(即获取用户列表的位置)。您可以使用
populate
或$lookup
急切地加载订阅,然后通过每个用户字段解析程序中的parent
参数可以使用订阅。感谢您的帮助,我将使用populate来限制数据库调用。