[英]How do I schedule a batch update to a collection in my Firebase Firestore database using Cloud Functions?
[英]How do I get the server timestamp in Cloud Functions for Firebase with 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
})
}
使用 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;
这是一个稍微更简洁的方法:
import * as admin from "firebase-admin"
const timestamp = admin.firestore.FieldValue.serverTimestamp();
这是我的做法。 它不需要将'@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()});
如果您使用的是 Firestore,则可以使用以下代码片段。
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore()
val ts = db.FieldValue.serverTimestamp()
如果您使用的是 "firebase-admin": "10.0.0" 您可以使用以下代码段。
const {FieldValue} = require('firebase-admin/firestore');
const timestamp = FieldValue.serverTimestamp();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.