relayjs and graphql error: Error: "Node" expects field "id"

1k views Asked by At

I think the issue is that the field in my schema.js file is called something other than 'id' because the field is called something else in the database.

var classroomType = new GraphQLObjectType({
  name: 'Classroom',
  description: 'A classroom in a school',
  fields: () => ({
    clid: globalIdField('Classroom'),
    course: {
      type: GraphQLString,
      description: 'The course assigned to this classroom.'
    },
    enrollments: {
      type: enrollmentConnection,
      description: 'The students in a classroom',
      args: connectionArgs,
      resolve: (classroom, args) => connectionFromArray(classroom.enrollments.map(getEnrollment), args)
    }
  }),
  interfaces: [nodeInterface],
});

Does the gloablIdField HAVE to be called id? That would seem strange. If so, how do I map that to an id field from the db not called id?

1

There are 1 answers

0
mparis On BEST ANSWER

If you need your global id field to be 'clid', you can either change the name of the id to clid in your Node interface or you can keep it id and apply an alias to the field in the resolver methods that hit your DB.

Option 1 would look like this:

interface MyNode {
  clid: ID!
}

type Classroom implements MyNode {
    clid: ID!
    ...
}

Option 2

The 'globalIdField' function exposed by graphql-relay accepts an idFetcher as second argument. You could change it to this:

id: globalIdField('Classroom', (obj, context, info) => obj.clid)

You would then also need to alias the id field to clid in your mutation resolvers as well.