The GraphQL Resolver function that returns an object

When querying with GraphQL, I receive results in the following format:

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

However, I would like to simplify the structure by removing the array for category:

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

Here is my current schema:

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

And the resolver function used:

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 have attempted to transform the array into an object but it was unsuccessful:

return { ...category }

If you have any suggestions or ideas, please help. Thank you.

Answer №1

Your resolver is set up to return an array:

export const Event = {
    type: async (parent, args, context, info) => {
        const dbTypes = await Type.find()
        const type = dbTypes.filter((type) => {
            return parent.type.includes(type.id)
        })
        return type
    }
}

Consider switching out filter for find

export const Event = {
    type: async (parent, args, context, info) => {
        const dbTypes = await Type.find()
        const type = dbTypes.find((type) => {
            return parent.type.includes(type.id)
        })
        return type
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for swapping out a div tag with another div tag in the same spot without needing to redirect to a different page by utilizing bootstrap

Currently, I am developing a JSP project that utilizes Bootstrap for the frontend. I have come across a question regarding HTML design. Is there a way to replace one div tag with another div on the same page without navigating to a new URL using Bootstrap ...

Interactive Div Updates Dropdown Selections Automatically

// function to add set of elements var ed = 1; function new_server() { ed++; var newDiv = $('#server div:first').clone(); newDiv.attr('id', ed); var delLink = '<a class="btn btn-danger" style="text-align:right;m ...

Enhancing static SVG with dynamic tooltips using D3.js

Our challenge involves adding tooltips dynamically to a static SVG image when a hover event occurs on an object within the SVG using d3.js in the context of an AngularJS application. The SVG image we are working with is a floorplan, which is quite intrica ...

Experience the frustration when the Ruby on Rails Open Modal Box Link fails to work. Stay tuned for the latest update on the link

My goal is to have a Modal Popup Box open when a specific link is clicked on my page. Here is the code I added to my view file: <%= link_to_remote '+ Add Discount', :url => {:controller => "parent_wise_fee_payments", :action => "ne ...

Obtaining a fresh access token from a refresh token using the googleapis npm library

I've been searching everywhere for an explanation, but I can't seem to find one. The documentation I've read says that refresh tokens are used to obtain new access tokens, but it doesn't explain the mechanics behind it. Normally, I wou ...

Is it possible to create an animation in NextJS using framer-motion that triggers only during the initial page load and resets every 12 hours?

My website has a main page that loads in with an exciting framer-motion animation. I'm trying to figure out how to make sure this animation only plays the first time the page is loaded, and not every time the page is refreshed or navigated back to. Si ...

How can datatables format a column by pulling from various sources? (Utilizing server side processing

Struggling to implement server-side processing with concatenated columns and encountering SQL errors. Came across a post discussing the issue: Datatables - Server-side processing - DB column merging Would like to insert a space between fields, is this ac ...

What could be causing my image not to show up on ReactJS?

I'm new to ReactJS and I am trying to display a simple image on my practice web app, but it's not showing up. I thought my code was correct, but apparently not. Below is the content of my index.html file: <!DOCTYPE html> <html> & ...

When encountering an OR operator, Javascript will cease execution of the remaining conditions

This is a basic JavaScript form-validation I created. All the document.form.*.value references are present on my page, except for the document.form.dasdasdas.value ==''. In the code below, the purpose is to display an error if any of the forms a ...

Unusual behavior of middleware in express 4 causing a strange dynamic effect

I've encountered an issue where a dynamically created middleware in an Express 4 route is not getting called and causing a timeout. 'use strict'; var bodyParser = require( 'body-parser' ); var logger = require( './logger&apo ...

a guide to presenting information in a horizontal layout within a single table using the Laravel framework and Vue.js

I have 2 tables: table 1 ________________ | name_id name | | 1 john | | 2 heaven | |_______________| table 2 _______________________ | id name_id product | | 1 1 bag | | 2 1 shoes | |______ ...

Transferring information from one page to the next

How can I efficiently transfer a large amount of user-filled data, including images, between pages in Next.js? I've searched through the Next.js documentation, but haven't found a solution yet. ...

Can you provide me with a step-by-step guide on how to implement Stripe's Custom Payment feature

Currently in the process of creating a customized payment module for my django application and in need of some assistance. At the moment, I am using Stripe's Checkout for handling payments, but I find it restrictive as it doesn't allow for comple ...

The sub-menu is being obscured by a PDF element in Internet Explorer, causing visibility issues

I have an object type tag on my page that displays a PDF file. Everything is functioning correctly, but in Internet Explorer, my sub-menu is being hidden behind the object tag. var objTag = $('<object></object>') .attr({ data: source ...

Using an AngularJS array with ng-repeat

As soon as a websocket message is received, the code below executes: connection.onmessage = function (eventInfo) { var onConnectionMessage = JSON.parse(eventInfo.data); if (onConnectionMessage.messageType === "newRequest") { getQuizRequests(); } } T ...

Problem with resizing in CSS and jQuery

I need help creating a chatbox that can be resized. I've almost got it, but the bottom part of the chatbox detaches when I resize it. Also, I'm having trouble making the userList a fixed size that won't be affected by resizing. Check out th ...

Following the ajax request, the subsequent code was unable to be executed as it awaited the JSON response

My latest project involves using Django2 to create a web application. I encountered an issue in the frontend where, despite receiving a 200 status code in the network tab after an ajax call, no alert box was displayed. The app seemed to be stuck at a parti ...

I'm sorry, but we were unable to locate the module: Error: Unable to find 'fs' in '/usr/src/app/node_modules/jpeg-exif/lib'

Encountering an error when building a react app on production: Module not found: Error: Can't resolve 'fs' in '/usr/src/app/node_modules/jpeg-exif/lib' Node Version: Node version 18 Steps taken in Docker Production: npm install - ...

Issue with Restangular/angularjs object not refreshing after remove() operation

I am currently using Restangular within my AngularJS application. I have an index view that displays all messages, and I can edit and add messages to the list without any issues. However, when I attempt to use the remove() function on an element, the index ...

Refresh the navigation bar on vuejs post-login

Creating a client login using Vue has been a challenge for me. My main component includes the navigation bar and the content rendering component. The navigation component checks if the user is logged in to display the buttons for guests and hide the button ...