可以在schema中定义Resolver,通过Projection选择与查询的字段保持一致的子文档。例如,假设我们有一个user集合,每个用户都有一个地址子文档集合,我们可以定义如下Resolver:
Query: {
users: (_, args, { db }) => {
return db.collection('users').find().toArray()
},
},
User: {
addresses: (parent, _, { db }, info) => {
const projection = Object.keys(info.fieldNodes[0].selectionSet.selections[0].selectionSet.selections[0].selectionSet.selections[0].selectionSet.selections[0].selectionSet).reduce((acc, current) => { // 通过Projection选择保留的字段
acc[current] = 1
return acc
}, {})
return db.collection('addresses').find({ userId: parent._id }).project(projection).toArray()
},
}
在这个例子中,我们在users Query中返回所有的用户,然后在User Resolver中选择与查询的addresses字段保持一致的子文档。通过projection,我们只返回与查询保持一致的字段,从而避免了返回整个子文档集合的问题。