0

I'm working on a project with GraphQl but have run into a problem with querying through GraphQl and sequelize. When trying to query associated objects i receive the following error:

Cannot return null for non-nullable field User.organisation.

But when I only query the User objects without the associations I get no error and everything works fine. Here is my code:

Query Code:

return await models.user.findAll({ include: [{ model: models.organisation, as: 'Creator'}]}); 

GraphQl query that works:

query{users{username}}

Graphql query that doesn't work:

query{users{username organisation{id}}}

When troubleshooting the error i found that when console logging the response from the database it shows like this: Where the Array of organizations simply are shown as an Array and not as the actual objects I'm looking for which is something i can't explain...

 dataValues:
     { id: 1,
       username: 'asdfasd',
       password: '$2b$10$ynFfJ8NFrSC7ycA0Xskjqu5uq.wegBuZkphkfMiG99F.vqN7Wqw9C',
       email: 'asdf@gmo.com',
       active: true,
       createdAt: 2018-11-25T16:42:32.140Z,
       updatedAt: 2018-11-25T16:42:32.140Z,
       Creator: [Array] },

Sequelize model Association definition:

  user.associate = function(models) {
    models.user.hasMany(models.organisation, {
      foreignKey: 'OrgAdmin',
      as: 'Creator'
    });

Any help would be much appreciated!

Oscar
  • 221
  • 2
  • 7
  • 18
  • Maybe read up on resolvers. If you don't supply a resolver the default resolvers will be `parent => parent[fieldName]`. Seems like you would rather want `parent => parent.Creator` because your field name is `organisations`. Maybe change `as: 'Creator'` to `as: 'organisations'` in the model association. Furthermore you might want to only make the join _if and only if_ the field is actually requested. _graphql-sequelize_ can help here but it is better to fully understand GraphQL's resolves first. – Herku Nov 25 '18 at 19:18
  • You're most probably missing an eager somewhere in your sequelize configuration. – Baldráni May 17 '19 at 04:44
  • Adding the `as: 'Creator'` option means each user object will include a `Creator` property, but GraphQL is expecting to find a property named `organization`. Either change the `as` value or add a resolver for the `organisation` field like @Herku pointed out. See [this answer](https://stackoverflow.com/questions/56319137/why-does-a-graphql-query-return-null/56319138#56319138) for additional details. – Daniel Rearden Jun 01 '19 at 16:18

0 Answers0