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:
"one"
Providing a field that doesn’t exist returns a Type
error:
does not have field
.
This group by UDF uses dot notation to group all customers by city, showing how to use dot notation to create anonymous functions:
|
Bracket notation field accessor
The following example uses bracket notation ([ ]
), passing the field name as
a string to access the field or property:
"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:
"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 book = {
name: 'Hamlet',
author: {
name: 'Shakespeare'
}
}
book.writer?.name
The example returns null
instead of an error provided type checking is
disabled.
Invoke an anonymous method example:
let book = {
name: 'Hamlet',
author: {
name: 'Shakespeare'
}
}
book.author.customMethod?.()
The example returns null
instead of an error provided type checking is
disabled.
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!