Graphql - 获取完整的子对象,如果不存在则为 null [英] Graphql - get full sub-object, or null if doesn't exist
问题描述
我有一个 graphql 查询,它使用 Client
对象获取 Meeting
对象:
type Meeting {地址:字符串!客户:客户}输入客户端{显示名称:字符串!}
displayName
是必需的,但 client
不是.如果我将其查询为
<代码>{getMeeting(会议ID:43bbea6ea0c6112b0abcf11d"){地址客户 {显示名称}}}
而且这次会议没有客户,那么我收到一个错误:
错误:无法为不可为 null 的字段 Client.displayName 返回 null.
我只是希望如果有客户,我会得到它的全部详细信息.如果没有,我会得到 client: null
.
如果我从 displayName
中删除所需的,它也会在客户端为空时工作,我会得到 p>
客户端":{显示名称":空}
正如我所料.但我仍在寻找一种方法来强制 displayName
上的要求 - 仅当有客户端时.
有没有办法在graphql中做到这一点?
所以问题出在mongoose
.
当我从数据库中获取数据时,猫鼬添加了 client: {}
的空嵌入子文档,即使 meeting
文档中没有这样的键在数据库中(并且 console.log(meeting)
不显示此字段 - 只有 console.log(meeting.client)
打印 client: {}
).
因此 graphql
尝试返回 client
的必填字段,因为 client
不是我想的 undefined
.
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?
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.
这篇关于Graphql - 获取完整的子对象,如果不存在则为 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!