简体   繁体   English

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

[英]How do I get the server timestamp in Cloud Functions for Firebase with Firestore?

How can we get a server timestamp, without using the realtime database but using instead 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
              })
            }

Use server timestamp with Firestore is little different:使用 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()
});

if it's not working you can edit the var FieldValue = require("firebase-admin").FieldValue;如果它不起作用,您可以编辑var FieldValue = require("firebase-admin").FieldValue; with var FieldValue = require("firebase-admin").firestore.FieldValue;使用var FieldValue = require("firebase-admin").firestore.FieldValue;

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

import * as admin from "firebase-admin"

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

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.它不需要将'@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()});

If you are using Firestore, you can use such below code snippet.如果您使用的是 Firestore,则可以使用以下代码片段。

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

val ts = db.FieldValue.serverTimestamp()

If you are using "firebase-admin": "10.0.0" You can use the below snippet.如果您使用的是 "firebase-admin": "10.0.0" 您可以使用以下代码段。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM