在Firestore中访问文档内部的集合

问题描述 投票:1回答:1

我有一个文档,并且在其中有一个称为relatives的集合。在云函数中,我有此文档的onUpdate()侦听器。更改某些内容后,我想在我的文档中访问该集合。以及集合relatives中的文档。

这是它的外观:

enter image description here


我尝试过的

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个回答
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);
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.