2

Graphql return Oject with null id. with mongodb.

It looks strange to me.

If I delete new GraphQLNonNull() on MailType id, It works with id: null, another fields working fine.

const MailType = new GraphQLObjectType({
    name: 'Mail',
    fields: () => ({
        id: { type: new GraphQLNonNull(GraphQLID), },
...
})

const Query = {
    mails: {
        type: new GraphQLList(MailType),
        args: {
            senderId: { type: GraphQLID },
            isOffline: { type: GraphQLBoolean },
        },
        async resolve(root, args, req, ctx) {
            if (args.isOffline === false) {
                let a = await model.aggregate([
                  { $match: { isOffline: false } },
                ]);
                let b = await model.find({ isOffline: false });

                console.log(JSON.stringify(a) == JSON.Stringify(b)) /// return true
                return a // error
                return b // working
            }
            return model.find({senderId: args.senderId});
        }
    }
}
// with a
    "errors": [
        {
            "message": "Cannot return null for non-nullable field Mail.id."
        }]

I am in trouble for 2 hours but I do not get the answer. Can anybody help me?

yusung lee
  • 236
  • 1
  • 12
  • It simply means that id field is null when you return `a`, which shouldn't be because you have defined id as `GraphQLNonNull` and hence the error. – Boney Jan 19 '19 at 09:32
  • @Boney a, b is array of mail. Both have mails with valid id. – yusung lee Jan 19 '19 at 11:25

1 Answers1

1

You probably have a mistake in your mongodb schema, not in graphQl. make sure you did not define you id by id key, it should be _id.

for example if you are using mongoose it can be something like this:

const MailSchema = new Schema({
  _id: {
    type: String,
    unique: true,
  },
  ....
  ....
});
Emad Emami
  • 6,089
  • 3
  • 28
  • 38