I talk about how to atomically increment/decrement values in FaunaDB.
Credit
Original answer here: https://news.ycombinator.com/item?id=24618998.
Code
Suppose you have an article
schema like so:
// Schema
Article {
slug: string;
likes: number;
}
To atomically increment likes
, you need to invoke Update()
with two parameters:
- Document reference
- Part of the document to be updated
For the value of the key to be updated, invoke Add()
with two parameters:
-
Select()
with the path to the key, to get the current value - Value to increment/decrement by (1 in our case; pass
-1
to decrement)
// Query
documentReference; // Assuming this is available
Update(
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:
// Query
Map(
Paginate(
Match(
Index('allArticles'),
'article-about-faunadb'
)
),
Lambda(
'X',
Update(
Var('X'),
{
data: {
likes: Add(
Select(['data', 'likes'], Get(Var('X'))),
1
)
}
}
)
)
)
Cheers!
Top comments (0)