【问题标题】:update cloud firestore document without id更新没有 ID 的云 Firestore 文档
【发布时间】:2019-06-29 16:11:11
【问题描述】:
我的 Cloud Firestore 如下所示:
users
├────random_id_1───{name, email, ...}
├────random_id_2───{name, email, ...}
...
└────random_id_n───{name, email, ...}
我想更新 users 的文档,因为我有一个唯一标识符,它不是文档的随机 id(例如,假设名称是唯一的,我想使用它作为标识符)。
如何更新通过字段标识的文档?
【问题讨论】:
标签:
javascript
firebase
google-cloud-firestore
google-cloud-functions
【解决方案1】:
Firestore 只能更新它知道完整引用的文档,这需要文档 ID。在您当前的结构上,您必须运行查询才能找到文档。所以像:
firebase.firestore().collection("users")
.where("name", "==", "Daniel")
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(document) {
document.ref.update({ ... });
});
});
如果您有另一个独特的属性,我总是建议将其用作文档的 ID。这样一来,您就可以自动保证每个用户只能存在一个文档,并且您不必执行查询来查找文档。