我有一个文档,并且在其中有一个称为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;
});
我想访问亲戚及其文件。因此,我可以搜索和比较字段并有意地对其进行更新。
要从DocumentSnapshot
获取子集合,必须先为该快照的文档获取DocumentReference
,然后在该快照下找到CollectionReference
。
使用代码:
change.after.ref.collection("relatives")
在这里:
change.after
为您提供修改后的文档的DocumentSnapshot
。change.after.ref
然后为您提供该文档的DocumentReference
,因此它在数据库中的位置。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);
});
});