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

时间:2017-10-09 13:42:21

标签: 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
              })
            }

4 个答案:

答案 0 :(得分:25)

使用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()
});

如果它不起作用,您可以使用var FieldValue = require("firebase-admin").FieldValue;

编辑var FieldValue = require("firebase-admin").firestore.FieldValue;

答案 1 :(得分:1)

这是一种更为简洁的方法:

import * as admin from "firebase-admin"

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

答案 2 :(得分:0)

如果您使用的是Firestore,则可以使用以下代码段。

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

val ts = db.FieldValue.serverTimestamp()

答案 3 :(得分:0)

这是我的方法。不需要将'@google-cloud/firestore'添加为项目的依赖项,并且无需在代码中添加大量admin.firestore.xxx

import * as admin from "firebase-admin";

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

someRef.set({timestamp: FieldValue.serverTimestamp()});
相关问题