This is an example document of my mongoDB. I need to get the content.en
array via Apollo/GraphQL. But the nested object is getting a problem for me.
en
is the language tag, so it would be great if this could be used as a variable.
Data in MongoDB
{
"_id" : "9uPjYoYu58WM5Tbtf",
"content" : {
"en" : [
{
"content" : "Third paragraph",
"timestamp" : 1484939404
}
]
},
"main" : "Dn59y87PGhkJXpaiZ"
}
The graphQL result should be:
{
"data": {
"article": [
{
"_id": "9uPjYoYu58WM5Tbtf",
"content": [
{
"content" : "Third paragraph",
"timestamp" : 1484939404
}
]
}
]
}
}
That means, I need to get the ID and the language specific content array.
But this is not, what I'm getting with the following setup:
Type
const ArticleType = new GraphQLObjectType({
name: 'article',
fields: {
_id: { type: GraphQLID },
content: { type: GraphQLString }
}
})
GraphQL Schema
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()
}
}
}
})
})
Query
{
article(id: "Dn59y87PGhkJXpaiZ") {
_id,
content
}
}
Result
{
"data": {
"article": [
{
"_id": "9uPjYoYu58WM5Tbtf",
"content": "[object Object]"
}
]
}
}
You can use below code.
Java Example:
I think the problem comes from this line:
content: { type: GraphQLString }
. Try extracting content to anotherGraphQLObjectType
and then pass it toArticleType
ascontent
fieldEdit
Try this:
Since you said that the language ISO code should be a parameter and that the content is depending on a language ISO code (I'll call it
languageTag
from now on), I figured that you should edit your schema to look something like this:However, this still does not fix your issue of retrieving the content. I reckon that you need to add another type to your schema called
ContentType
.One final issue I would like to bring up is that you are returning a single
article
as anArray
. I would suggest to change this to return a single object. Last but not least, your schema would look something like this:This code could be a little bit off, since I do not have your database to test it. I think that it is a good push in the right direction.