Jayanta Baishya
Jayanta Baishya

Reputation: 97

How to define GraphQLObjectType for a nested object or list of objects in the same parent object

For my MongoDB object, I have a schema where so many nested data are there.

however I implemented perfectly in GraphQL for the query to get the data, but I am unable to fetch the nested data as I am unable to define the types.

fields() {
        return {
            name: {
                type: GraphQLString,
                description: 'Name of the person'
            },
            age: {
                type: GraphQLString,
                description: 'Age'
            },
            documents: { // what to do here
                type: new GraphQLList(),
                description: 'All documents for the person'
            }
       }
}

The original data is something like this.

{
    "_id" : ObjectId("5ae1da5e4f00b5eee4ab84ee"),
    "name" : "Indira Gandhi International Airport",
    "age" : 54,
    "documents" : [
        {
             "doc_name" : "personal card",
             "doc_url" : "http://",
             "status" : true
        },
        {
             "doc_name" : "bank card",
             "doc_url" : "http://",
             "status" : true
        }
     ],
    "latitude" : "",
    "longitude" : "",
    "timezone" : "Asia/kolkata"
    .......
}

I am new in graphQL, please help.

Upvotes: 4

Views: 1616

Answers (1)

ericArbour
ericArbour

Reputation: 703

I believe what you are trying to do here is have your documents field be a list of documents. In order to do this, you need to create a "document" GraphQLObjectType to pass into new GraphQLList() in your documents field. Like so:

const DocumentType = new GraphQLObjectType({
  name: 'DocumentType',
  fields: {
    doc_name: {
      type: GraphQLString
    },
    doc_url: {
      type: GraphQLString
    },
    status: {
      type: GraphQLBoolean
  }
});

Then once you have that created, either in the same file (or in a different file and imported necessarily) with the right dependencies, you plug it into the code you posted above like so:

fields() {
        return {
            name: {
                type: GraphQLString,
                description: 'Name of the person'
            },
            age: {
                type: GraphQLString,
                description: 'Age'
            },
            documents: {
                type: new GraphQLList(DocumentType),
                description: 'All documents for the person'
            }
       }
}  

I hope this helps.

Upvotes: 6

Related Questions