Skip to content

Helper Functions

Helper functions provide powerful data transformation and manipulation capabilities within template expressions. Functions are prefixed with @ and used inside template brackets.

Overview

Helper Functions - Built-in functions for data transformation, formatting, calculations, and validation. Used within template expressions to manipulate document data dynamically.

Where helper functions are used:

  • Template Expressions - Inside {{ }}, ?{{ }}, or $ shorthand syntax
  • Mutations - Transform data in db.update, db.upsert, db.insert
  • Output Projection - Format query results in db.find

Helper syntax:

json
{
  "uuid": "{{ @uuid() }}",
  "uppercase_name": "{{ @uppercase(name) }}",
  "item_count": "?{{ @len(items) }}",
  "formatted_date": "{{ @formatdate(created_at, 'YYYY-MM-DD') }}"
}

Function Syntax

Helper functions are prefixed with @ and called within template brackets:

json
{
  "result": "{{ @function(arg1, arg2) }}"
}

Document data access: Document fields are passed as arguments to helper functions:

json
{
  "uppercase_name": "{{ @uppercase(firstname) }}",
  "full_name": "{{ @concat(firstname, ' ', lastname) }}",
  "email_valid": "?{{ @isemail(email) }}"
}

Nested functions: Helper functions can be nested for complex operations:

json
{
  "uuid_length": "?{{ @len(@uuid7()) }}",
  "uppercase_trim": "{{ @uppercase(@trim(name)) }}",
  "formatted_title": "{{ @titlecase(@lowercase(title)) }}"
}

Note: Avoid deeply nested functions for better readability. For complex transformations, break into multiple fields.


Functions Quick Reference

Date and Time:

FunctionDescription
@now()Current UTC datetime
@formatdate(dt, format)Format date using specified format
@shiftdate(date, shift)Shift date by time expression
@timestamp()Current timestamp in seconds
@diffdates(d1, d2, unit)Calculate difference between dates

ID Generation:

FunctionDescription
@uuid()Generate UUID4 (no dashes)
@uuid4()Generate UUID4 (with dashes)
@uuid7()Generate UUID7
@shortid()Generate short ID (8 chars)
@hash(text)Generate SHA-256 hash

String Manipulation:

FunctionDescription
@tostring(value)Convert value to string
@uppercase(text)Convert to uppercase
@lowercase(text)Convert to lowercase
@titlecase(text)Convert to title case
@capitalize(text)Capitalize first letter
@maskstr(text, visible, char)Mask text except last N chars
@trim(text)Remove whitespace
@len(value)Get length of string/array/object
@startswith(text, prefix)Check if starts with prefix
@endswith(text, suffix)Check if ends with suffix
@substring(text, start, end)Get substring
@replace(text, old, new)Replace text
@contains(text, substring)Check if contains substring
@slugify(text)Convert to URL-friendly slug
@striphtml(html)Remove HTML tags
@truncate(text, n, suffix)Truncate to n words
@concat(v1, v2, ...)Concatenate values

Encoding:

FunctionDescription
@b64encode(text)Encode to base64
@urlencode(text)URL encode text

Conditional Logic:

FunctionDescription
@cond(cond, t, f)If-else expression
@default(val, def)Return value or default if null
@isnot(value)Logical NOT

Number Operations:

FunctionDescription
@tocurrency(amount, curr)Format as currency
@topercent(value, decimals)Format as percentage
@tonumber(value, decimals)Format number with separators
@toint(value, default)Convert to integer
@tofloat(value, default)Convert to float
@toordinal(value)Convert to ordinal (1st, 2nd, 3rd)
@abs(x)Absolute value
@round(x)Round to nearest integer
@floor(x)Round down
@random(min, max)Random integer in range

Collection Operations:

FunctionDescription
@sum(array)Sum of array values
@avg(array)Average of array values
@min(array)Minimum value
@max(array)Maximum value
@sortby(array, key, rev)Sort array by property
@groupby(array, key)Group array by property
@unique(array, key)Get unique values

Validation:

FunctionDescription
@isempty(value)Check if empty
@isnull(value)Check if null/none/empty
@isemail(value)Validate email
@isurl(value)Validate URL

Date and Time Functions

@now() - Current DateTime

Get current UTC datetime.

json
{
  "created_at": "{{ @now() }}",
  "timestamp": "?{{ @now() }}"
}

Example:

json
{
  "op": "db.insert",
  "collection": "events",
  "data": {
    "name": "User Login",
    "occurred_at": "{{ @now() }}"
  }
}

Output: "2024-01-15T10:30:00.000Z"


@formatdate(dt, format) - Format Date

Format a date using specified format string.

json
{
  "formatted": "{{ @formatdate(created_at, 'YYYY-MM-DD') }}",
  "readable": "{{ @formatdate(timestamp, 'MMMM DD, YYYY') }}"
}

Common formats:

  • YYYY-MM-DD - 2024-01-15
  • YYYY/MM/DD - 2024/01/15
  • MMMM DD, YYYY - January 15, 2024
  • MMM DD, YYYY - Jan 15, 2024
  • YYYY-MM-DD HH:mm:ss - 2024-01-15 10:30:00

Example:

json
{
  "op": "db.find",
  "collection": "orders",
  "output": {
    "order_id": "$order_id",
    "order_date": "{{ @formatdate(created_at, 'MMMM DD, YYYY') }}",
    "time": "{{ @formatdate(created_at, 'HH:mm:ss') }}"
  }
}

@shiftdate(date, shift) - Shift Date

Shift a date by a specified amount of time, forward or backward.

json
{
  "expires": "{{ @shiftdate(@now(), '+7days') }}",
  "reminder": "{{ @shiftdate(due_date, '-1day') }}"
}

Shift expression syntax:

Format: [+/-]<number><unit>

Units:

  • year, years, y
  • month, months, M
  • week, weeks, w
  • day, days, d
  • hour, hours, h
  • minute, minutes, min, m
  • second, seconds, sec, s

Examples:

Single unit:

json
{
  "tomorrow": "{{ @shiftdate(@now(), '+1day') }}",
  "last_week": "{{ @shiftdate(@now(), '-7days') }}",
  "next_month": "{{ @shiftdate(@now(), '+1month') }}"
}

Multiple units:

json
{
  "future": "{{ @shiftdate(@now(), '1year 2months -5days') }}",
  "mixed": "{{ @shiftdate(@now(), '-3hours +30minutes') }}"
}

Spaces optional:

json
{
  "shifted": "{{ @shiftdate(@now(), '1day-3hours+30min') }}"
}

Unit accumulation:

json
{
  "total": "{{ @shiftdate(@now(), '2hours 3hours') }}"
}
// Results in 5 hours shift

Case insensitive:

json
{
  "date": "{{ @shiftdate(@now(), '1YEAR 2MONTHS') }}"
}

Example:

json
{
  "op": "db.insert",
  "collection": "subscriptions",
  "data": {
    "user_id": "user_123",
    "started_at": "{{ @now() }}",
    "expires_at": "{{ @shiftdate(@now(), '+1year') }}",
    "reminder_at": "{{ @shiftdate(@now(), '+11months 23days') }}"
  }
}

@timestamp() - Current Timestamp

Get current Unix timestamp in seconds.

json
{
  "ts": "?{{ @timestamp() }}"
}

Example:

json
{
  "op": "db.update",
  "collection": "sessions",
  "filter": { "_key": "session_123" },
  "data": {
    "last_active": "?{{ @timestamp() }}"
  }
}

Output: 1705320600


@diffdates(d1, d2, unit) - Date Difference

Calculate difference between two dates.

json
{
  "days_diff": "?{{ @diffdates(end_date, start_date, 'days') }}",
  "hours_diff": "?{{ @diffdates(deadline, @now(), 'hours') }}"
}

Units: years, months, weeks, days, hours, minutes, seconds

Example:

json
{
  "op": "db.find",
  "collection": "projects",
  "output": {
    "name": "$name",
    "days_remaining": "?{{ @diffdates(deadline, @now(), 'days') }}",
    "overdue": "?{{ @diffdates(deadline, @now(), 'days') < 0 }}"
  }
}

ID Generation Functions

@uuid() - Generate UUID (No Dashes)

Generate UUID4 without dashes.

json
{
  "tracking_id": "{{ @uuid() }}"
}

Output: 550e8400e29b41d4a716446655440000


@uuid4() - Generate UUID4 (With Dashes)

Generate standard UUID4 with dashes.

json
{
  "id": "{{ @uuid4() }}"
}

Output: 550e8400-e29b-41d4-a716-446655440000


@uuid7() - Generate UUID7

Generate time-ordered UUID7.

json
{
  "event_id": "{{ @uuid7() }}"
}

Output: Time-sortable UUID


@shortid() - Generate Short ID

Generate short 8-character ID.

json
{
  "code": "{{ @shortid() }}"
}

Output: aB3xY9k2


@hash(text) - Generate Hash

Generate SHA-256 hash of text.

json
{
  "fingerprint": "{{ @hash(content) }}",
  "checksum": "{{ @hash(@concat(id, secret)) }}"
}

Example:

json
{
  "op": "db.insert",
  "collection": "documents",
  "data": {
    "content": "Important data",
    "content_hash": "{{ @hash(content) }}"
  }
}

String Manipulation Functions

@uppercase(text) - Uppercase

Convert text to uppercase.

json
{
  "code": "{{ @uppercase(country_code) }}",
  "name": "{{ @uppercase(firstname) }}"
}

Example:

json
{
  "op": "db.update",
  "collection": "users",
  "filter": { "_key": "user_123" },
  "data": {
    "country": "{{ @uppercase(country) }}"
  }
}

Input: "united states"
Output: "UNITED STATES"


@lowercase(text) - Lowercase

Convert text to lowercase.

json
{
  "email": "{{ @lowercase(email) }}",
  "tag": "{{ @lowercase(category) }}"
}

Input: "ADMIN@EXAMPLE.COM"
Output: "admin@example.com"


@titlecase(text) - Title Case

Convert text to title case.

json
{
  "title": "{{ @titlecase(name) }}"
}

Input: "hello world"
Output: "Hello World"


@capitalize(text) - Capitalize First Letter

Capitalize only the first letter.

json
{
  "sentence": "{{ @capitalize(description) }}"
}

Input: "hello world"
Output: "Hello world"


@maskstr(text, visible, char) - Mask String

Mask text except last N characters.

json
{
  "masked_card": "{{ @maskstr(card_number, 4) }}",
  "masked_email": "{{ @maskstr(email, 3, '*') }}"
}

Parameters:

  • text - String to mask
  • visible - Number of characters to keep visible (from end)
  • char - Masking character (default: *)

Example:

json
{
  "card": "{{ @maskstr('4532123456789012', 4) }}"
}

Output: "************9012"


@trim(text) - Trim Whitespace

Remove whitespace from both ends.

json
{
  "clean_name": "{{ @trim(name) }}"
}

Input: " John Doe "
Output: "John Doe"


@len(value) - Get Length

Get length of string, array, or object.

json
{
  "name_length": "?{{ @len(name) }}",
  "item_count": "?{{ @len(items) }}",
  "field_count": "?{{ @len(metadata) }}"
}

Example:

json
{
  "op": "db.find",
  "collection": "posts",
  "output": {
    "title": "$title",
    "tag_count": "?{{ @len(tags) }}",
    "has_tags": "?{{ @len(tags) > 0 }}"
  }
}

@concat(v1, v2, ...) - Concatenate

Concatenate multiple values.

json
{
  "full_name": "{{ @concat(firstname, ' ', lastname) }}",
  "address": "{{ @concat(street, ', ', city, ', ', zip) }}"
}

Example:

json
{
  "op": "db.update",
  "collection": "users",
  "filter": { "_key": "user_123" },
  "data": {
    "display_name": "{{ @concat(firstname, ' ', lastname) }}",
    "location": "{{ @concat(city, ', ', country) }}"
  }
}

@slugify(text) - Create Slug

Convert text to URL-friendly slug.

json
{
  "slug": "{{ @slugify(title) }}"
}

Input: "Hello World! This is a Test"
Output: "hello-world-this-is-a-test"

Example:

json
{
  "op": "db.insert",
  "collection": "articles",
  "data": {
    "title": "My Blog Post",
    "slug": "{{ @slugify(title) }}"
  }
}

@striphtml(html) - Remove HTML Tags

Remove HTML tags from text.

json
{
  "plain_text": "{{ @striphtml(content) }}"
}

Input: "<p>Hello <b>World</b></p>"
Output: "Hello World"


@truncate(text, n, suffix) - Truncate Text

Truncate text to n words with optional suffix.

json
{
  "preview": "{{ @truncate(description, 20, '...') }}"
}

Parameters:

  • text - Text to truncate
  • n - Number of words
  • suffix - Suffix to add (default: ...)

Example:

json
{
  "summary": "{{ @truncate(content, 50, ' [Read more]') }}"
}

@substring(text, start, end) - Get Substring

Extract substring using slice notation.

json
{
  "first_three": "{{ @substring(code, 0, 3) }}",
  "last_four": "{{ @substring(number, -4) }}"
}

Example:

json
{
  "year": "{{ @substring(date, 0, 4) }}"
}

@replace(text, old, new) - Replace Text

Replace occurrences of text.

json
{
  "clean": "{{ @replace(text, 'bad', 'good') }}"
}

Example:

json
{
  "formatted": "{{ @replace(phone, '-', '') }}"
}

@contains(text, substring) - Check Contains

Check if text contains substring.

json
{
  "has_admin": "?{{ @contains(role, 'admin') }}"
}

Returns: Boolean


@startswith(text, prefix) - Starts With

Check if text starts with prefix.

json
{
  "is_https": "?{{ @startswith(url, 'https') }}"
}

Returns: Boolean


@endswith(text, suffix) - Ends With

Check if text ends with suffix.

json
{
  "is_pdf": "?{{ @endswith(filename, '.pdf') }}"
}

Returns: Boolean


Encoding Functions

@b64encode(text) - Base64 Encode

Encode text to base64.

json
{
  "encoded": "{{ @b64encode(data) }}"
}

Input: "Hello World"
Output: "SGVsbG8gV29ybGQ="


@urlencode(text) - URL Encode

URL encode text.

json
{
  "encoded_url": "{{ @urlencode(search_query) }}"
}

Input: "hello world"
Output: "hello%20world"


Conditional Logic Functions

@cond(cond, t, f) - Conditional

If-else conditional expression.

json
{
  "status": "{{ @cond(active, 'Active', 'Inactive') }}",
  "discount": "?{{ @cond(is_member, 0.2, 0.1) }}"
}

Example:

json
{
  "op": "db.find",
  "collection": "users",
  "output": {
    "name": "$name",
    "status": "{{ @cond(verified, 'Verified ✓', 'Not Verified') }}",
    "discount_rate": "?{{ @cond(premium, 0.2, 0.1) }}"
  }
}

@default(val, def) - Default Value

Return value or default if null/empty.

json
{
  "display_name": "{{ @default(nickname, name) }}",
  "count": "?{{ @default(items, 0) }}"
}

Example:

json
{
  "country": "{{ @default(user_country, 'US') }}"
}

@isnot(value) - Logical NOT

Logical NOT operation.

json
{
  "inactive": "?{{ @isnot(active) }}"
}

Returns: Boolean


Number Operations Functions

@tocurrency(amount, curr) - Format Currency

Format number as currency.

json
{
  "price": "{{ @tocurrency(total, 'USD') }}",
  "euro_price": "{{ @tocurrency(amount, 'EUR') }}"
}

Example:

json
{
  "formatted_price": "{{ @tocurrency(99.99, 'USD') }}"
}

Output: "$99.99"


@topercent(value, decimals) - Format Percentage

Format number as percentage.

json
{
  "completion": "{{ @topercent(progress, 1) }}",
  "discount": "{{ @topercent(0.15, 0) }}"
}

Example:

json
{
  "rate": "{{ @topercent(0.875, 2) }}"
}

Output: "87.50%"


@tonumber(value, decimals) - Format Number

Format number with thousand separators.

json
{
  "views": "{{ @tonumber(view_count, 0) }}",
  "price": "{{ @tonumber(amount, 2) }}"
}

Example:

json
{
  "formatted": "{{ @tonumber(1234567, 0) }}"
}

Output: "1,234,567"


@toint(value, default) - Convert to Integer

Convert value to integer.

json
{
  "count": "?{{ @toint(user_input, 0) }}"
}

Example:

json
{
  "age": "?{{ @toint(age_string, 18) }}"
}

@tofloat(value, default) - Convert to Float

Convert value to float.

json
{
  "price": "?{{ @tofloat(price_string, 0.0) }}"
}

@toordinal(value) - Convert to Ordinal

Convert number to ordinal (1st, 2nd, 3rd).

json
{
  "position": "{{ @toordinal(rank) }}"
}

Input: 1
Output: "1st"

Input: 23
Output: "23rd"


@abs(x) - Absolute Value

Get absolute value.

json
{
  "distance": "?{{ @abs(difference) }}"
}

@round(x) - Round Number

Round to nearest integer.

json
{
  "rounded": "?{{ @round(price) }}"
}

Input: 99.7
Output: 100


@floor(x) - Round Down

Round down to integer.

json
{
  "floored": "?{{ @floor(value) }}"
}

Input: 99.9
Output: 99


@random(min, max) - Random Number

Generate random integer in range.

json
{
  "lucky_number": "?{{ @random(1, 100) }}"
}

Example:

json
{
  "op": "db.insert",
  "collection": "games",
  "data": {
    "player": "user_123",
    "dice_roll": "?{{ @random(1, 6) }}"
  }
}

Collection Operations Functions

@sum(array) - Sum Array

Sum of array values.

json
{
  "total": "?{{ @sum(prices) }}"
}

Example:

json
{
  "op": "db.find",
  "collection": "orders",
  "output": {
    "order_id": "$order_id",
    "total": "?{{ @sum(@map(items, 'price * quantity')) }}"
  }
}

@avg(array) - Average

Average of array values.

json
{
  "average_score": "?{{ @avg(scores) }}"
}

@min(array) - Minimum Value

Get minimum value from array.

json
{
  "lowest_price": "?{{ @min(prices) }}"
}

@max(array) - Maximum Value

Get maximum value from array.

json
{
  "highest_score": "?{{ @max(scores) }}"
}

@sortby(array, key, rev) - Sort Array

Sort array by property.

json
{
  "sorted_users": "?{{ @sortby(users, 'age', false) }}",
  "sorted_desc": "?{{ @sortby(products, 'price', true) }}"
}

Parameters:

  • array - Array to sort
  • key - Property to sort by
  • rev - Reverse order (true/false)

@groupby(array, key) - Group Array

Group array by property.

json
{
  "by_category": "?{{ @groupby(products, 'category') }}"
}

@unique(array, key) - Unique Values

Get unique values from array.

json
{
  "unique_tags": "?{{ @unique(tags) }}",
  "unique_users": "?{{ @unique(orders, 'user_id') }}"
}

Validation Functions

@isempty(value) - Check Empty

Check if value is empty.

json
{
  "has_description": "?{{ @isnot(@isempty(description)) }}"
}

Returns: Boolean


@isnull(value) - Check Null

Check if value is null/none/empty.

json
{
  "has_value": "?{{ @isnot(@isnull(field)) }}"
}

Returns: Boolean


@isemail(value) - Validate Email

Validate email address format.

json
{
  "valid_email": "?{{ @isemail(email) }}"
}

Returns: Boolean


@isurl(value) - Validate URL

Validate URL format.

json
{
  "valid_url": "?{{ @isurl(website) }}"
}

Returns: Boolean


Common Patterns

User Display Name

json
{
  "op": "db.find",
  "collection": "users",
  "output": {
    "display": "{{ @concat(@titlecase(firstname), ' ', @uppercase(@substring(lastname, 0, 1)), '.') }}",
    "email_lower": "{{ @lowercase(@trim(email)) }}"
  }
}

Order Summary

json
{
  "op": "db.insert",
  "collection": "orders",
  "data": {
    "order_id": "{{ @uuid4() }}",
    "items": [
      { "name": "Widget", "price": 29.99, "qty": 2 }
    ],
    "subtotal": "?{{ @sum(@map(items, 'price * qty')) }}",
    "tax": "?{{ @round(@sum(@map(items, 'price * qty')) * 0.08) }}",
    "total": "?{{ @sum(@map(items, 'price * qty')) + @round(@sum(@map(items, 'price * qty')) * 0.08) }}",
    "formatted_total": "{{ @tocurrency(total, 'USD') }}",
    "created_at": "{{ @now() }}",
    "expires_at": "{{ @shiftdate(@now(), '+7days') }}"
  }
}

Content Preview

json
{
  "op": "db.find",
  "collection": "articles",
  "output": {
    "title": "{{ @titlecase(title) }}",
    "slug": "{{ @slugify(title) }}",
    "preview": "{{ @truncate(@striphtml(content), 50) }}",
    "word_count": "?{{ @len(@split(content, ' ')) }}",
    "published": "{{ @formatdate(published_at, 'MMMM DD, YYYY') }}"
  }
}

Security and Privacy

json
{
  "op": "db.find",
  "collection": "users",
  "output": {
    "name": "$name",
    "masked_email": "{{ @maskstr(email, 4, '*') }}",
    "masked_phone": "{{ @maskstr(phone, 4, 'X') }}",
    "account_hash": "{{ @hash(@concat(email, created_at)) }}"
  }
}

Best Practices

Use Appropriate Return Types

For text formatting:

json
{
  "message": "{{ @uppercase(status) }}"
}

For calculations:

json
{
  "total": "?{{ @sum(prices) }}"
}

Avoid Deep Nesting

Good - readable:

json
{
  "clean_name": "{{ @titlecase(@trim(name)) }}"
}

Avoid - too complex:

json
{
  "result": "{{ @uppercase(@substring(@replace(@trim(text), 'old', 'new'), 0, 10)) }}"
}

For complex operations, break into multiple fields.

Combine with Template Expressions

Helper functions work seamlessly with template expressions:

json
{
  "full_info": "{{ @titlecase(name) }} - {{ @formatdate(created_at, 'YYYY-MM-DD') }}",
  "is_eligible": "?{{ @len(items) > 0 && @sum(@map(items, 'price')) >= 100 }}",
  "$display": "@concat(name, ' (', @toordinal(rank), ')')"
}

Notes

  • All helper functions are prefixed with @
  • Document fields are automatically available as function arguments
  • Functions can be nested, but avoid deep nesting
  • Use ? for functions returning numbers or booleans
  • Use for functions returning strings
  • See Template Expressions for more on expression syntax