How do I get the server timestamp in Cloud Functio

2020-02-04 11:20发布

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
              })
            }

2条回答
▲ chillily
2楼-- · 2020-02-04 11:32

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

import * as admin from "firebase-admin"

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

查看更多
beautiful°
3楼-- · 2020-02-04 11: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;

查看更多
登录 后发表回答