Collection()
Dynamically get the Collection by name.
Description
The Collection()
method gets the name collection.
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
instance methods.
In most cases, you should use <collectionName>
. However, Collection()
is
useful if you need to iterate through a list of collection names.
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
instance 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!