GraphQL relay return one record

706 Views Asked by At

I using graphql-relay in my project

When run this query in my grapgql:

{
  viewer{
    boRelayCustomerInfo(_id:"59267769de82262d7e39c47c") {
      edges {
        node {
          id
        }
      }
    } 
  }
}

I gave this error: "message": "arraySlice.slice is not a function"

My Query code is :

import {
  GraphQLID,
  GraphQLNonNull,
} from 'graphql'

import {
  connectionArgs,
  connectionFromPromisedArray,
} from 'graphql-relay'


import { customerConnection } from '@/src/schema/type/customer/CustomerType'
import { CustomerModel, ObjectId } from '@/src/db'


export default {
  type: customerConnection.connectionType,
  args: {
    ...connectionArgs,
    _id: {
      type: new GraphQLNonNull(GraphQLID),
    },
  },
  resolve: (_, args) => connectionFromPromisedArray(
    CustomerModel.findOne({_id: ObjectId(args._id)}),
    args,
  ),
}

please tell us, how to return only one record in relay.

1

There are 1 best solutions below

0
Rajan Maharjan On

As stated in the official document graphql-relay-js

connectionFromPromisedArray takes a promise that resolves to an array

so, the problem here is with the first parameter passed in the connectionFromPromisedArray method. ie: CustomerModel.findOne({_id: ObjectId(args._id)})

where findOne returns an object, instead you need to use find to get the response as an array.

Problem code:

  resolve: (_, args) => connectionFromPromisedArray(
    CustomerModel.findOne({_id: ObjectId(args._id)}), // <=== Error
    args,
  ),

Solution to the problem:

 resolve: (_, args) => connectionFromPromisedArray(
    CustomerModel.find({_id: ObjectId(args._id)}), // <=== Solution
    args,
  ),

Hope it helps :)