How to get server timestamp in cloud functions for Firebase with Firestore?

How can we get the server’s timestamp without using a real-time database but using Firestore instead?

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
              })
            }
+11
source share
2 answers

Using a server timestamp with Firestore is a 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 does not work, you can edit var FieldValue = require("firebase-admin").FieldValue;withvar FieldValue = require("firebase-admin").firestore.FieldValue;

+25
source

Here is a slightly shorter way to do this:

import * as admin from "firebase-admin"

const timestamp = admin.firestore.FieldValue.serverTimestamp();

0
source

All Articles