2
votes

I have a node.js server that uses sequelize and graphql to provide GraphQL endpoint.

Somehow object fields that are linked with belongsTo are always null in GraphQL query output.

Here are my graphql typedefs:

type Student {
  id: ID!
  name: String!
  age: Int!
  schoolClass: SchoolClass
}

type SchoolClass {
  id: ID!
  title: String!
}

Here is how sequelize model defined

const SchoolClass = sequelize.define('SchoolClass', {
  title: Sequelize.STRING
});

const Student = sequelize.define('Student', {
  name: Sequelize.STRING,
  age: Sequelize.TINYINT
});

Student.belongsTo(SchoolClass);

The resolver is

students (root, args, context) {
    return models.Student.findAll({}, context);
}

The query:

{ 
  students { 
    id, name, age, schoolClass { id } 
  } 
}

Typical output:

{
  "data": {
    "students": [
      {
        "id": "1",
        "name": "John",
        "age": "18",
        "schoolClass": null
      }
    ]
  }
}

Is there any way to get actual data instead of nulls?

1
does Student table has class_id/classId ? - Vivek Doshi
@VivekDoshi yes, it has SchoolClassId field with appropriate IDs filled in (I renamed Class to SchoolClass not to confuse this entity with JS Class) - Dmitry Samoylov
Check this out : github.com/mickhansen/graphql-sequelize , think this will help you - Vivek Doshi

1 Answers

2
votes

By default, Sequelize does not populate any fields created by relationships when calling findAll. You have to use the include option to specify which relationships you want to include the query. See the docs for more info.

Additionally, findAll only takes one argument (an options object), and I'm not quite sure what you're trying to do by passing your context to the model. This should be sufficient to get all Students with their associated schoolClass:

return models.Student.findAll({ include: [ 'SchoolClass' ] })

Check out the reference for findAll for more info about what options you can use.