1
votes

In my Cloud Firestore database, i have a collection of documents including a created timestamp.

Env.docRef.collection('collect').add({
            name: this.name,
            active: true,
            created: firebase.firestore.FieldValue.serverTimestamp()
    }).then(function(docRef) {
           ......;
    }.bind(this));

When i need to update/disable one document, i would like to create a duration field that represent the time since the document was created.

 Env.docRef.collection('collect').doc(this.id).update({
                active: false,
                ended: firebase.firestore.FieldValue.serverTimestamp(),
                duration : ???
            }).then(function() {
                ....;
            })
            .catch(function(error) {
               ....;
            });

Is there any option to build this duration in the query ?

1

1 Answers

0
votes

There is not a simple token for duration like there is with server timestamp. If you want to use server timestamps for both the created and ended fields, what you will have to do is read the document after it's fully written, do math on the timestamps, and write the duration back into the document.

Or, you don't need that duration field to be indexed for querying, you can simply let other clients do the date match at the time they read the document in order to display the data.

Note that, when doing date math with timestamps, there is both a seconds and nanosecond field for timestamps in Firestore. If you want to preserve nanosecond precision, you will have to be careful about doing more than just a simple subtraction.