Reputation: 379
I have a document, and inside of it there is a collection called relatives
. In cloud functions, I have onUpdate()
listener for this document. Once something is changed, I want to access that collection inside of my document. Also documents in the collection relatives
.
Here is how it looks like:
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;
});
I want to access relatives and its documents. So I can search and compare field and update them on purpose.
Upvotes: 1
Views: 2073
Reputation: 598688
To get a subcollection from a DocumentSnapshot
, you must first get a DocumentReference
to the document for that snapshot, and then find the CollectionReference
under that.
In code:
change.after.ref.collection("relatives")
In here:
change.after
gives you the DocumentSnapshot
of the modified document.change.after.ref
then gives you the DocumentReference
of that document, so its location in the database.change.after.ref.collection("relatives")
then gives you the CollectionReference
to the relatives
subcollection of the document.So get data from these subcollections you'll have to actually load that data, it is not already included in the change
object that is passed to your function.
So if you want to load all relatives for the user that triggered the function, it'd be something like:
let relativesRef = change.after.ref.collection("relatives");
return relatives.get().then((querySnapshot) => {
querySnapshot.forEach((relativeDoc) => {
console.log(doc.id, doc.data().relativeaccount);
});
});
Upvotes: 2