Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the server timestamp in Cloud Functions for Firebase with Firestore?

Tags:

How can we get a server timestamp, without using the realtime database but using instead Firestore ?

import * as functions from 'firebase-functions'
import { Firestore } from '@google-cloud/firestore'

const db = new Firestore()

export let testIfMatch = functions.firestore
        .document('users/{userId}/invites/{invitedUid}')
        .onCreate(event => {
            let invite = <any>event.data.data()

            if (invite.accepted == true) {
              return db.collection('matches').add({
                friends: [userId, invitedUid],
                timestamp: doc.readTime // <--- not exactly the actual time
              })
            }
like image 472
Thomas Avatar asked Oct 09 '17 13:10

Thomas


People also ask

How do I get firestore timestamp?

firestore. FieldValue. serverTimestamp() you can use . toDate() .

How do I find my Firebase server date?

To reach the timestamp of firebase server on client, you first need to write the value to the server then read the value. firebase. database(). ref('currentTime/').

What is the format of firestore timestamp?

Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.


1 Answers

Use server timestamp with Firestore is little different:

// Get the `FieldValue` object
var FieldValue = require("firebase-admin").FieldValue;

// Create a document reference
var docRef = db.collection('objects').doc('some-id');

// Update the timestamp field with the value from the server
var updateTimestamp = docRef.update({
    timestamp: FieldValue.serverTimestamp()
});

if it's not working you can edit the var FieldValue = require("firebase-admin").FieldValue; with var FieldValue = require("firebase-admin").firestore.FieldValue;

like image 73
Fred van Rijswijk Avatar answered Sep 27 '22 20:09

Fred van Rijswijk