24

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
              })
            }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Thomas
  • 1,509
  • 4
  • 15
  • 25

5 Answers5

42

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;

10

Here's a slightly more concise way of doing it:

import * as admin from "firebase-admin"

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

Lindauson
  • 2,963
  • 1
  • 30
  • 33
1

Here's my way of doing it. It doesn't require adding '@google-cloud/firestore' as a dependency to your project, and eliminates adding lots of admin.firestore.xxx to your code.

import * as admin from "firebase-admin";

import FieldValue = admin.firestore.FieldValue;
// import anything else you want to alias

someRef.set({timestamp: FieldValue.serverTimestamp()});
Jack Guo
  • 3,959
  • 8
  • 39
  • 60
0

If you are using Firestore, you can use such below code snippet.

const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore()

val ts = db.FieldValue.serverTimestamp()
allsoft
  • 198
  • 1
  • 10
0

If you are using "firebase-admin": "10.0.0" You can use the below snippet.

const {FieldValue} = require('firebase-admin/firestore');
const timestamp = FieldValue.serverTimestamp();
mustaphahawi
  • 297
  • 1
  • 8