Automatically converting Time to String?

I am creating an Document with Create that inserts a Time value into a document. I would like to have the returned Time values be converted to String so I can directly return from API:

        const query = await client.query(
            q.Create(q.Collection("MyCollection"), {
                data: {
                    date: q.Time(transactionDate), // how to make this return String in return document
                },
            })
        );

How do I ensure return type of date is String so I don’t have to write extra FQL that selects the date field and invokes Format

Use the ToString | Fauna Documentation function.

For example:

> Time('2021-06-30T20:01:06.174Z')
Time("2021-06-30T20:01:06.174Z")
> ToString(Time('2021-06-30T20:01:06.174Z'))
'2021-06-30T20:01:06.174Z'
1 Like

@ewan maybe the point of my post was unclear. Do I have to use Select to apply that to a particular field on the output of the Create operation? I would like to store in FaunaDB as a Time type to get all the benefits of time stamp based queries.

Nothing in Fauna is “automatic”: you have to write your queries to achieve your goals in explicit ways.

You are using q.Time to convert transactionDate to a time. If transactionDate is a string, just use that instead of calling q.Time. If not, then use q.ToString(q.Time(transactionDate)). That would guarantee that the value stored in the date field is a string.

An alternative would be to continue storing date as you are currently, but then create a new index that includes a binding, perhaps named date_str, that calls ToString on the value of the date field. Then you would have both values available. It would increase your storage and write ops a bit to do so, but seems more flexible.

@ewan thanks for clarifying that is what I was expecting and I agree by design. Less “magic” the better. Sort of a side question here, what JavaScript data type is the returned value for Time data type? Does it have any helpful functions?

The type is a FaunaTime. Unfortunately, there aren’t really any helpful functions associated. Here’s the entire implementation: faunadb-js/values.js at master · fauna/faunadb-js · GitHub

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.