您对Let 和Merge 的使用表明您正在以一种好的方式考虑FQL。这些函数可以大大提高您的查询的组织性和可读性!
我将从一些笔记开始,但它们与最终答案相关,所以请坚持我。
Query 函数
https://docs.fauna.com/fauna/current/api/fql/functions/query
首先,您不需要在 Query 函数中包装任何内容,这里。 Query 是在 FQL 中定义稍后将运行的函数所必需的,例如,在用户定义函数 body 中。您将始终将其视为Query(Lambda(...))。
动物群 ID
https://docs.fauna.com/fauna/current/learn/understanding/documents
请记住,Fauna 会为您为每个文档分配唯一的 ID。当我看到名为id 的字段时,这有点危险,所以我想强调一下。您可能会在文档中存储一些企业 ID 的原因有很多,但请确保您需要它。
获取 ID
Fauna 中的文档形状如下:
{
ref: Ref(Collection("users"), "101"), // <-- "id" is 101
ts: 1641508095450000,
data: { /* ... */ }
}
在JS驱动中你可以通过documentResult.ref.id来使用这个id(其他驱动也可以用类似的方式)
您也可以直接在 FQL 中访问 ID。您使用Select 函数。
Let(
{
user: Get(Select(['user_id'], Var('oauthInfo')))
id: Select(["ref", "id"], Var("user"))
},
Var("id")
)
更多关于 Select 函数的信息。
https://docs.fauna.com/fauna/current/api/fql/functions/select
您已经在使用Select,这就是您正在寻找的功能。它是您用来抓取对象或数组的任何部分的工具。
这是一个人为的示例,用于获取集合中第三个用户的邮政编码:
Let(
{
page: Paginate(Documents(Collection("user")),
},
Select(["data", 2, "data", "address", "zip"], Var("user"))
)
把它放在一起
也就是说,您的Let 函数是一个很好的开始。让我们把事情分解成更小的步骤。
Let(
{
oauthInfo_ref: Ref(Collection('user_oauth_info'), refId)
oauthInfo_doc: Get(Var("oathInfoRef")),
// make sure that user_oath_info.user_id is a full Ref, not just a number
user_ref: Select(["data", "user_id"], Var("oauthInfo_doc"))
user_doc: Get(Var("user_ref")),
user_id: Select("id", Var("user_ref")),
// calculate expired
expiry_date: Select(["data", "expiry_date"], Var("user_doc")),
has_expired: LT(Now(), Var("expiry_date"))
},
// if the data does not overlap, Merge is not required.
// you can build plain objects in FQL
{
oauthInfo: Var("oauthInfo_doc"), // entire Document
user: Var("user_doc"), // entire Document
has_expired: Var("has_expired") // an extra field
}
)
如果您确实想合并它们和/或添加其他字段,而不是将身份验证信息和用户作为单独的点返回,然后随意这样做
// ...
Merge(
Select("data", Var("user_doc")), // just the data
{
user_id: Var("user_id"), // added field
has_expired: Var("has_expired") // added field
}
)
)