Field accessors and method chaining
This section covers field accessors and method chaining.
Field access
Accessors can be viewed as keys for referencing fields or properties in an associative array, dictionary, or lookup table. In Fauna documents, fields can be accessed using dot notation or bracket notation.
Dot notation field accessor
The dot prefix (.
) preceding the field name is used to access a field or
property, as shown by the .aKey
notation in this example:
let object = {
aKey: "one",
bKey: "two"
}
object.aKey
"one"
Providing a field that doesn’t exist returns an error.
Bracket notation field accessor
The following example uses bracket notation ([ ]
), passing the field name as
a string to access the field or property:
let object = {
aKey: "one",
bKey: "two"
}
object["aKey"]
"one"
Providing a field that doesn’t exist returns null
.
Using bracket notation allows you to dynamically access document fields as shown in this example:
let object = {
aKey: "one",
bKey: "two"
}
let x = "aKey"
object[x]
"one"
Method chaining
Methods can be chained using dot notation to compose complex queries where the output of the previous method is the input of the next method.
In this example, the query returns up to ten documents from all the documents
in the Product
collection:
Product.all().take(10)
Anonymous field and method access
A variant of dot notation, the
optional chaining operator can be used
to access a field or invoking a method, returning null
instead of an error if
the left side of the expression evaluates to null
.
Access an anonymous field example:
let customer = {
name: "Alice Appleseed",
address: {
state: "DC"
}
}
customer.address?.state // Returns "DC"
Is this article helpful?
Tell Fauna how the article can be improved:
Visit Fauna's forums
or email docs@fauna.com
Thank you for your feedback!