[英]Retrieving Cloud Firestore `timestamp` value after save
假設我要向 Cloud Firestore 添加一些數據:
import { collection, addDoc, serverTimestamp } from 'firebase/firestore';
const ref = await addDoc(collection(db, 'posts'), {
createdAt: serverTimestamp(),
modifiedAt: null,
title: 'A Title',
});
我有規則強制執行createdAt
應該等於request.time
並且永遠不會更新, modifiedAt
在創建時應該是null
但在更新時等於request.time
,而title
應該是一個字符串。
當我嘗試更新此文檔時出現問題:
import { doc, updateDoc } from 'firebase/firestore';
await updateDoc(ref, {
createdAt: ???, // what goes here?
modifiedAt: serverTimestamp(),
title: 'A Title',
});
我需要createdAt
作為初始服務器時間戳值(作為Date
對象)。 我不能只放置serverTimestamp()
,因為 Firestore 會嘗試將該字段更新為新的request.time
值,規則執行將失敗。 我無法進行部分更新(通過省略createdAt
),因為我使用的是客戶端 ORM(Ember 數據),它無法像這樣處理部分更新。
有沒有一種方法可以檢索調用addDoc
后初始serverTimestamp
值變成的任何值,而無需在addDoc
之后立即發出第二個請求來檢索我們剛剛創建的文檔? 似乎沒有必要提出第二個請求,因為我已經擁有所有數據(沒有時間戳值)。 我基本上只是試圖避免在每次創建新記錄時在整個應用程序范圍內添加第二個請求。
updateDoc
操作(不同於addDoc
操作或默認的setDoc
操作)只會覆蓋您實際指定的鍵。 因此,要按原樣保留createdAt
,只需將其省略即可。
await updateDoc(ref, {
modifiedAt: serverTimestamp(),
title: 'A Title',
});
要從您的 CRM 中提取密鑰,請對密鑰使用delete
。
const dataToUpdate = {
createdAt: "somevalue",
modifiedAt: serverTimestamp(),
title: 'A Title'
}
delete dateToUpdate.createdAt;
await updateDoc(ref, dataToUpdate);
此外,緊隨其后添加getDoc
並不像您想象的那樣昂貴。 如果您的應用程序在您的應用程序的任何地方使用該文檔(監聽文檔本身或其父集合),您的客戶端應用程序將收到通知並將更新的數據存儲在其本地緩存中,無論您是否在添加后立即需要它.
const ref = await addDoc(collection(db, 'posts'), {
createdAt: serverTimestamp(),
modifiedAt: null,
title: 'A Title',
});
const snapshotWithServerTimestamps = await getDoc(ref);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.