【发布时间】:2018-04-06 17:04:55
【问题描述】:
这是我的 mongoDB 的示例文档。我需要通过 Apollo/GraphQL 获取 content.en 数组。但是嵌套对象对我来说是个问题。
en 是语言标签,如果可以作为变量使用就好了。
MongoDB 中的数据
{
"_id" : "9uPjYoYu58WM5Tbtf",
"content" : {
"en" : [
{
"content" : "Third paragraph",
"timestamp" : 1484939404
}
]
},
"main" : "Dn59y87PGhkJXpaiZ"
}
graphQL 结果应该是:
{
"data": {
"article": [
{
"_id": "9uPjYoYu58WM5Tbtf",
"content": [
{
"content" : "Third paragraph",
"timestamp" : 1484939404
}
]
}
]
}
}
也就是说,我需要获取 ID 和特定语言的内容数组。
但这不是,我通过以下设置得到的结果:
类型
const ArticleType = new GraphQLObjectType({
name: 'article',
fields: {
_id: { type: GraphQLID },
content: { type: GraphQLString }
}
})
GraphQL 架构
export default new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
article: {
type: new GraphQLList(ArticleType),
description: 'Content of article dataset',
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLID)
}
},
async resolve ({ db }, args) {
return db.collection('articles').find({ main: args.id }).toArray()
}
}
}
})
})
查询
{
article(id: "Dn59y87PGhkJXpaiZ") {
_id,
content
}
}
结果
{
"data": {
"article": [
{
"_id": "9uPjYoYu58WM5Tbtf",
"content": "[object Object]"
}
]
}
}
【问题讨论】:
-
您希望查询返回什么?您能否将其添加到您的问题中?
-
@DevNebulae 我已经发布了。请参阅第二个代码块。 "graphQL 结果应该是"
-
我相信您需要两个参数,id 参数来过滤根解析上的文章和语言参数来过滤子解析上的内容。因此 mongo 查询将返回所有匹配的文章 id 与所有语言内容,graphql 将返回基于语言 arg 的内容。还将内容映射到架构。
标签: javascript mongodb graphql apollo-server