在firebase中,我们可以根据字段的值来更新字段而不读取它(没有本地副本)吗?例如,我有一个
doc
,其 points
字段等于 5
。我想将 1
添加到 points
字段。有没有办法用 updateDoc(doc(db, ... ))
更新它,而无需先用 getDoc
阅读?
对于数字字段,您可以使用
increment
操作。在模块化 JavaScript 中,这是:
import { doc, updateDoc, increment } from "firebase/firestore";
const washingtonRef = doc(db, "cities", "DC");
// Atomically increment the population of the city by 50.
await updateDoc(washingtonRef, {
population: increment(50)
});
有关更多示例,请参阅 Google Cloud 上的文档:Increment a Firestore document field 和 Firebase 的文档:Increment a numeric value(这就是我获取上述示例的来源)。