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

Posted

技术标签:

【中文标题】如何使用 Firestore 在 Cloud Functions for Firebase 中获取服务器时间戳?【英文标题】:How do I get the server timestamp in Cloud Functions for Firebase with Firestore? 【发布时间】:2018-03-20 18:03:44 【问题描述】:

我们如何在不使用实时数据库的情况下获取服务器时间戳 但改用 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
              )
            

【问题讨论】:

【参考方案1】:

在 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").firestore.FieldValue; 编辑var FieldValue = require("firebase-admin").FieldValue;

【讨论】:

谢谢,require("firebase-admin").firestore.FieldValue; 有效,但 require("firebase-admin").FieldValue; 无效 @GrafOrlov 我编辑了,因为文档没有firestore 是的,require("firebase-admin").firestore.FieldValue.serverTimestamp(); 是正确的。 你能解释一下这个包 firebase-admin,我应该把它导入 app.module 吗?安装此软件包后ng serve 停止工作,我收到很多错误 @PiniCheyni 对不起,读错了...不,这是为了在云功能中使用它,而不是在 Angular 中,使用 AngularFire 2 【参考方案2】:

这里有一个更简洁的方法:

import * as admin from "firebase-admin"

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

【讨论】:

【参考方案3】:

这是我的做法。它不需要将'@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());

【讨论】:

【参考方案4】:

如果你使用的是 Firestore,你可以使用下面这样的代码 sn-p。

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

val ts = db.FieldValue.serverTimestamp()

【讨论】:

【参考方案5】:

如果您使用的是“firebase-admin”:“10.0.0” 你可以使用下面的sn-p。

const FieldValue = require('firebase-admin/firestore');
const timestamp = FieldValue.serverTimestamp();

【讨论】:

以上是关于如何使用 Firestore 在 Cloud Functions for Firebase 中获取服务器时间戳?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Cloud Firestore 中使用文档 ID 执行集合组查询

如何使用flutter cloud_firestore包传递firestore auth token

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

如何在 Cloud Firestore 中使用 Stream 回调

如何使用 Firebase Cloud Firestore 对方法进行单元测试?

查询时如何在 Flutter (Dart) 中使用变量 Cloud Firestore