Check out v4 of the Fauna CLI
v4 of the Fauna CLI is now in beta. The new version introduces enhancements to the developer experience, including an improved authentication workflow. To get started, check out the CLI v4 quick start. |
Collection()
Access a collection by its name.
Description
Accesses a collection by its name. You can chain collection name methods to the returned collection.
Errors
If you attempt to access a collection that doesn’t exist, Fauna returns a query
runtime error with an invalid_argument
error code and a 400 HTTP status
code:
invalid_argument
error: invalid argument `collection`: No such user collection `Foo`.
at *query*:1:11
|
1 | Collection("Foo")
| ^^^^^^^
|
Comparison to <collectionName>
Calling Collection()
is similar to accessing <collectionName>
directly,
except:
-
Collection()
returns an Any value -
<collectionName>
is a Collection value
This difference only affects static typing, not runtime behavior. Both
Collection()
and <collectionName>
support the same
collection
name methods.
In most cases, you should use <collectionName>
. However, Collection()
is
useful if you need to iterate through a list of collection names. See
Dynamically specify a collection name.
Return value
Type | Description |
---|---|
The named collection. You can chain collection name methods to the returned collection. |
Examples
Collection()
returns an Any value. For example:
Collection("Product")
Returns an Any value:
Product
Difference with <collectionName>
Accessing <collectionName>
directly returns a similar value, typed as a
Collection. For example:
Product
Returns the Product
Collection value:
Product
Method chaining
In most cases, you’ll chain other
collection
name methods to Collection()
. For example:
let produce = Category.byName("produce").first()
Collection("Product").create({
name: "zebra pinata",
description: "Giant Zebra Pinata",
price: 23_99,
stock: 0,
category: produce
})
Returns an Any value:
{
id: "12345",
coll: Product,
ts: Time("2099-06-24T21:21:37.170Z"),
name: "zebra pinata",
description: "Giant Zebra Pinata",
price: 2399,
stock: 0,
category: Category("789")
}
Dynamically specify a collection name
Use Collection()
to dynamically specify collection names in a query.
For example, the following
user-defined function (UDF)
uses Collection()
to pass a collection name as an argument:
// Accepts a collection name as an argument.
function getPriceLowtoHigh(collection) {
// Uses `Collection()` to dynamically specify
// the collection name.
Collection(collection).sortedByPriceLowToHigh() {
price,
name,
description
}
}
The following query calls the function:
// Calls the `getPriceLowtoHigh()` UDF with
// a `Product` collection argument.
getPriceLowtoHigh("Product")
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!