【问题标题】:Accessing a collection inside of a document in firestore访问firestore中文档内的集合
【发布时间】:2020-06-03 00:42:52
【问题描述】:

我有一个文档,其中有一个名为relatives 的集合。在云功能中,我有 onUpdate() 的此文档的侦听器。更改某些内容后,我想访问文档中的该集合。还有集合中的文档relatives

这是它的样子:


我尝试过的

exports.UpdateLocations = functions.firestore.document("users/{userID}").onUpdate((change, context) => {
    const userEmail = change.after.data().email;
    const prevLocation = change.before.data().userLocation;
    const currentLocation = change.after.data().userLocation;

    if (prevLocation === currentLocation) return 0;

    if (change.after.data().userType.toString() === "Patient") {
        const userLocation = change.after.data().userLocation;
        const relatives = change.after.data().relatives;

        console.log("User's Current Location: " + userLocation);
        console.log("Relatives : "+relatives );

    }
    return;

});


我想访问亲属及其文件。所以我可以搜索和比较字段并有目的地更新它们。

【问题讨论】:

  • 与其用文字描述你想要做什么,你能用代码展示你已经做了什么以及你卡在哪里了吗?这样就更有可能有人告诉你哪里出错了,或者为你完成。
  • 我没有给出代码块的原因是我基本上坚持访问文档中的集合。我改变了我的结构,我以前的所有代码都变得一团糟。但是如果给它带来改变,我现在就添加它。

标签: firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

要从DocumentSnapshot 中获取子集合,您必须首先为该快照的文档获取DocumentReference,然后在其下找到CollectionReference

在代码中:

change.after.ref.collection("relatives")

在这里:

  1. change.after 为您提供修改后文档的DocumentSnapshot
  2. 然后change.after.ref 为您提供该文档的DocumentReference,以及它在数据库中的位置。
  3. change.after.ref.collection("relatives") 然后将CollectionReference 提供给文档的relatives 子集合。

因此,从这些子集合中获取数据,您必须实际加载该数据,它尚未包含在传递给您的函数的 change 对象中。

因此,如果您想为触发该功能的用户加载所有亲属,则类似于:

let relativesRef = change.after.ref.collection("relatives");
return relatives.get().then((querySnapshot) => {
  querySnapshot.forEach((relativeDoc) => {
    console.log(doc.id, doc.data().relativeaccount);
  });
});

【讨论】:

  • 太棒了!非常感谢弗兰克。这就是我要找的。​​span>
猜你喜欢
  • 2022-01-05
  • 2019-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
  • 2020-09-20
相关资源
最近更新 更多