Graphql-获取完整的子对象,如果不存在则返回null [英] Graphql - get full sub-object, or null if doesn't exist
问题描述
我有一个graphql查询,它使用Client
对象获取一个Meeting
对象:
I have a graphql query which gets a Meeting
object with Client
object:
type Meeting {
address: String!
client: Client
}
type Client {
displayName: String!
}
displayName
是必需的,但不是client
.
如果我将其查询为
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.
我只希望有一个客户,我将提供其详细信息.如果没有,我会得到client: null
.
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
.
如果我从displayName
中删除了必填项,则在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
}
"client": {
"displayName": null
}
如我所料.但我仍在寻找一种在displayName
上强制执行必需的方法-仅在有客户端的情况下.
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.
在graphql中有什么方法可以做到吗?
Is there any way to do that in graphql?
推荐答案
所以问题出在mongoose
上.
当我从数据库中获取数据时,猫鼬会添加client: {}
的空嵌入式子文档,即使数据库中meeting
文档中没有这样的键(并且console.log(meeting)
也不显示此内容)字段-仅console.log(meeting.client)
打印client: {}
).
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: {}
).
因此,graphql
尝试返回client
的必填字段,因为client
不是我所认为的undefined
.
Hence graphql
tries to return the required field of client
, because client
is not undefined
as I thought.
这篇关于Graphql-获取完整的子对象,如果不存在则返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!