如何使用Firestore获取Cloud Functions for Firebase中的服务器时间戳?

Tho*_*mas 14 javascript firebase google-cloud-functions google-cloud-firestore

如何在不使用实时数据库但使用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
              })
            }
Run Code Online (Sandbox Code Playgroud)

Fre*_*ijk 31

使用Firestore的服务器时间戳略有不同:

// 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()
});
Run Code Online (Sandbox Code Playgroud)

如果它不工作,你可以编辑var FieldValue = require("firebase-admin").FieldValue;var FieldValue = require("firebase-admin").firestore.FieldValue;

  • 谢谢,`require("firebase-admin").firestore.FieldValue;`工作,但`require("firebase-admin").FieldValue;`不 (4认同)
  • 是的,`require("firebase-admin").firestore.FieldValue.serverTimestamp();` 是正确的。 (2认同)

Lin*_*son 7

这是一个稍微更简洁的方法:

import * as admin from "firebase-admin"

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