我试图找出一种处理查询和 mongdb 投影的干净方法,这样我就不必从数据库中检索过多的信息。所以假设我有:
// the query
type Query {
getUserByEmail(email: String!): User
}
我有 aUser
和email
a username
,以保持简单。如果我发送查询并且只想检索电子邮件,我可以执行以下操作:
query { getUserByEmail(email: "test@test.com") { email } }
但是在解析器中,我的数据库查询仍然检索username
和email
,但只有其中一个被阿波罗服务器作为查询结果传回。
我只希望数据库检索查询要求的内容:
// the resolver
getUserByEmail(root, args, context, info) {
// check what fields the query requested
// create a projection to only request those fields
return db.collection('users').findOne({ email: args.email }, { /* projection */ });
}
当然,问题是,获取有关客户请求的信息并不是那么简单。
假设我将请求作为上下文传递 - 我考虑使用context.payload
具有查询字符串的 (hapi.js) 并通过各种.split()
s 搜索它,但这感觉有点脏。据我所知,info.fieldASTs[0].selectionSet.selections
有字段列表,我可以检查它是否存在。我不确定这有多可靠。特别是当我开始使用更复杂的查询时。
有没有更简单的方法?
如果您不使用 mongDB,则投影是您传入的附加参数,明确告诉它要检索什么:
// telling mongoDB to not retrieve _id
db.collection('users').findOne({ email: 'test@test.com' }, { _id: 0 })
一如既往,感谢这个了不起的社区。