Graphql - get full sub-object, or null if doesn

2019-06-08 08:05发布

问题:

I have a graphql query which gets a Meeting object with Client object:

type Meeting {
  address: String!
  client: Client
}
type Client {
  displayName: String!
}

The displayName is required, but client isn't. If I'm querying it as

{
  getMeeting(meetingId: "43bbea6ea0c6112b0abcf11d") {
    address
    client {
      displayName
    }
  }
}

And this meeting doesn't have a client, then I'm getting an error:

Error: Cannot return null for non-nullable field Client.displayName.

I just want that if there is a client, I will get its full details. And if there isn't, I will get client: null.

If I will remove the required from the displayName, it will work also when client is null and I will get

"client": { "displayName": null }

as I've expected. But I'm still looking for a way to enforce the required on the displayName - only if there is a client.

Is there any way to do that in graphql?

回答1:

So the problem was because of mongoose.

When I'm fetching the data from the DB, mongoose adds the empty embedded subdocument of client: {} even if there is no such key in the meeting document in the DB (and console.log(meeting) doesn't show this field - Only console.log(meeting.client) prints client: {}).

Hence graphql tries to return the required field of client, because client is not undefined as I thought.