Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

GraphQL Resolver return object

Actually, when I do a request with GraphQL I have a result like this :

{
  "data": {
    "events": [
      {
        "_id": "65f0653eb454c315ad62b416",
        "name": "Event name",
        "category": [
          {
            "_id": "66056f64c74b2fb603ba1f59",
            "name": "Category 1"
          }
        ]
      }
    ]
  }
}

But I have only one category by event, so I would like to transform the result like this, without array for category

{
  "data": {
    "events": [
      {
        "_id": "65f0653eb454c315ad62b416",
        "name": "Event name",
        "category":
          {
            "_id": "66056f64c74b2fb603ba1f59",
            "name": "Category 1"
          }
      }
    ]
  }
}

For now, here is my schema

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type Event {
    _id: String!
    name: String!
    category: [Category]!
}

And my resolver

export const Event = {
    category: async (parent, args, context, info) => {
        const dbCategories = await Category.find()
        const category = dbCategories.filter((category) => {
            return parent.category.includes(category.id)
        })
        return category
    }
}

I try to transform the array in object but it doesn’t work

return { ...category }

Do you have some ideas to help me ?

Thank a lot

>Solution :

Your resolver returns an array:

export const Event = {
    category: async (parent, args, context, info) => {
        const dbCategories = await Category.find()
        const category = dbCategories.filter((category) => {
            return parent.category.includes(category.id)
        })
        return category
    }
}

Try to replace filter by find

export const Event = {
    category: async (parent, args, context, info) => {
        const dbCategories = await Category.find()
        const category = dbCategories.find((category) => {
            return parent.category.includes(category.id)
        })
        return category
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading