Atomic Increment/Decrement in FaunaDB

Karma
1 min readFeb 3, 2021

--

I talk about how to atomically increment/decrement values in FaunaDB.

FaunaDB logo
FaunaDB logo

Credit

Original answer here: https://news.ycombinator.com/item?id=24618998.

Code

Suppose you have an article schema like so:

// SchemaArticle {
slug: string;
likes: number;
}

To atomically increment likes, you need to invoke Update() with two parameters:

  1. Document reference
  2. Part of the document to be updated

For the value of the key to be updated, invoke Add() with two parameters:

  1. Select() with the path to the key, to get the current value
  2. Value to increment/decrement by (1 in our case; pass -1 to decrement)
// QuerydocumentReference; // Assuming this is availableUpdate(
documentReference,
{
data: {
likes: Add(
Select(['data', 'likes'], Get(documentReference)),
1
)
}
}
)

In situations when the document reference is not known, and you’re obtaining it as an output of another function, call Update() in Lambda(). For example, suppose you have an Index allArticles with terms as data.slug in order to be able to find documents by slug. To atomically increment likes in all matched documents:

// QueryMap(
Paginate(
Match(
Index('allArticles'),
'article-about-faunadb'
)
),
Lambda(
'X',
Update(
Var('X'),
{
data: {
likes: Add(
Select(['data', 'likes'], Get(Var('X'))),
1
)
}
}
)
)
)

Cheers!

--

--

Karma
Karma

Responses (1)