A question about queries
I am querying for documents that have a nested (related) document. In my query, neither doc exists. When using projection to get the nested document, it throws an error about null.
Here there are no project
docs, and no event
event
docs. event
in the query is the related document.
Project.by_owner(User.byId("402523960858640449")) {
event { id, name, notes },
id,
moments,
recipients,
senderAddress,
name
}
Is there a better (more graceful) way of handling this case?
the error message
invalid_query
error: Type `Null` does not have field `name`
at *query*:2:17
|
2 | event { id, name, notes },
| ^^^^
|
hint: Use the ! or ?. operator to handle the null case
|
2 | event { id, !name, notes },
| +
|
In the interest of documenting things, via discord,
this is a known bug. if you want to work around it you can cast project
or project.event
to Any
and project off that:
Project.by_owner(User.byId("402523960858640449")).map(project=>{
let event = if (project.event != null) {
let event: Any = project.event // this effectively "turns off" typechecking for the `event` variable.
event { id, name, notes } // note that this will let you project anything, even fields that don't exist.
} else {
null
}
project {
id,
moments,
recipients,
senderAddress,
name,
event: event
}
})
we don’t have a casting operating like as
yet, but you can upcast variables with explicit types in a let
, which means you’ll be able to use Any
here to work around this. i realize its a bit ugly, but i think it’ll work here
Hello @nichoth. It looks like you received your answer in Discord, but to copy things here:
This is a known bug in the type system we are working on. Even null
or nullable types can be projected
![image](https://global.discourse-cdn.com/business4/uploads/fauna1/original/2X/0/03d1ddb3034b7496075962246af69a9b7d255ee8.png)
But there is an issue with the type checker not allowing it in some cases.
If you want to work around it you can cast project
or project.event
to Any
and project off that:
Project.by_owner(User.byId("402523960858640449")).map(project=>{
let event = if (project.event != null) {
let event: Any = project.event // this effectively "turns off" typechecking for the `event` variable.
event { id, name, notes } // note that this will let you project anything, even fields that don't exist.
} else {
null
}
project {
id,
moments,
recipients,
senderAddress,
name,
event: event
}
})
we don’t have a casting operating like as
yet, but you can upcast variables with explicit types in a let
, which means you’ll be able to use Any
here to work around this.
1 Like
Hello,
Thanks for sharing the solution, this is very helpful for me.
This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.