Dmitry Samoylov
Dmitry Samoylov

Reputation: 1318

node.js graphql/sequelize server returns null for linked properties

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?

Upvotes: 2

Views: 832

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84687

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.

Upvotes: 2

Related Questions