GraphQL Apollo Cannot Return Null for non-nullable [duplicate]

GraphQL Apollo Cannot Return Null for non-nullable [duplicate]

This question already has an answer here:

Why does a GraphQL query return null?

1 answer

I’m trying to learn graphql so that I can apply it to a React website. I’m having some trouble right now with it though and cannot figure out why it says that null is being returned when I am 100% certain that what is being returned is not null. If I print results in the resolver it prints an array of user objects as expected, but when it returns it says that I’m returning null for the field Query.users. Any help would be appreciated.
Query: { // graphql query resolver
users: function (parent, args, { User }) {
var mongoose = require(‘mongoose’);
var array = [];
mongoose.connect(‘localhost:27017’, function(err){
if(err) throw err;
User.find({}).then(results=>{
console.log(results);
return results;
});
});
}
}

type Query { //query typedef
users: [User]!
}

type User { // graphql schema typedef
_id: String!
username: String!,
email: String!,
joined: String,
interests: [String],
friends: [User]
}

var User = new Schema({ // mongoose schema def
username: !String,
email: !String,
joined: String,
interests: [String],
friends: [[this]]
});

Solutions/Answers:

Solution 1:

It is because you are not returning anything in your users function.

You can await and return the resolved promise value like below. Try this and check if you still are not able to get the users list from your query.

users: function (parent, args, { User }) {
  return await getUsers()
}


const getUsers = () => {
  var mongoose = require('mongoose');
  return new Promise((resolve, reject) => {
    mongoose.connect('localhost:27017', function(err){
      if(err) 
        reject(err);  
      User.find({}).then(results=>{
        console.log(results);
        resolve(results);
      });
    });        
  });  
}

The code I added has ES6, please convert it to ES5 if that is what you use through out your app.

Related:  schema.graphql file can't be found (node graphql-yoga)

References