更新没有 ID 的云 Firestore 文档

Dan*_*iel 1 javascript firebase google-cloud-functions google-cloud-firestore

我的 Cloud Firestore 如下所示:

users
  ?????random_id_1???{name, email, ...}
  ?????random_id_2???{name, email, ...}
 ...
  ?????random_id_n???{name, email, ...}
Run Code Online (Sandbox Code Playgroud)

我想更新用户文档,因为我有一个唯一标识符,它不是文档的随机 ID(例如,假设名称是唯一的,我想将其用作标识符)。

如何更新通过字段标识它的文档?

Fra*_*len 5

Firestore 只能更新它知道完整引用的文档,这需要文档 ID。在您当前的结构上,您必须运行查询才能找到文档。所以像:

firebase.firestore().collection("users")
  .where("name", "==", "Daniel")
  .get()
  .then(function(querySnapshot) {
    querySnapshot.forEach(function(document) {
     document.ref.update({ ... }); 
    });
  });
Run Code Online (Sandbox Code Playgroud)

如果您有另一个唯一的属性,我总是建议使用它作为文档的 ID。这样您就可以自动保证每个用户只能存在一个文档,并且您不必进行查询来查找文档。