Fauna is the first document-relational database, offering the benefits of document and relational databases in a package attractive to developers. Unlike other document databases, documents stored in Fauna can reference each other based on attributes, allowing developers to use arbitrarily complex joins in the database layer and eliminating the need for multiple round trips and custom join logic in application code. All requests execute in the context of a transaction, which means that the result is guaranteed to be consistent and up-to-date at the snapshot time of the request.
Fauna allows you to create first class relationships between collections. In this article, we go over examples of how to create relationships between collections.
Consider two collections: Book
and Author
. An example Author
document looks like this:
{
id: "367986698777264193",
coll: Author,
ts: Time("2023-06-19T18:11:53.410Z"),
name: "Charles Dickens",
isAlive: false
}
Let’s say you want to create a new Book
"David Copperfield" and reference the Author
"Charles Dickens" in that document.
You simply put the “Charles Dickens” Author
document in the Book
object directly.
Book.create({
title: "David Copperfield",
language: "English",
author: Author.firstWhere(.name == "Charles Dickens"),
genre: "fiction"
})
Output:
>> SUCCESS
{
id: "367986770965430337",
coll: Book,
ts: Time("2023-06-19T18:13:02.250Z"),
title: "David Copperfield",
Language: "English",
author: Author.byId("367986698777264193"),
genre: "fiction"
}
Notice that when you query for a Book
, only the references to related documents are returned.
Book.all().first()
>> SUCCESS
{
id: "367986770965430337",
coll: Book,
ts: Time("2023-06-19T18:38:44Z"),
title: "David Copperfield",
language: "English",
author: Author.byId("367986698777264193"),
genre: "fiction"
}
However, Fauna will automatically dereference relationships when you select fields in a related document. For example, in the following query, notice how you can project fields from a related document without having to deal with document references or foreign keys yourself.
Book.all().first(){
title,
genre,
author
}
The output of this query shows that he relationship was automatically resolved and the fields from the related documents were returned in the query:
>> SUCCESS
{
title: "David Copperfield",
genre: "fiction",
author: {
id: "367986698777264193",
coll: Author,
ts: Time("2023-06-19T18:11:53.410Z"),
name: "Charles Dickens",
isAlive: false
}
}