I have the following trigger firing when a field is updated in the notifications collection. After it does what it needs to do, I want to set 1 field to false for that same document that was updated. Is this the simplest way to do this? I know I have change.after
available, but not sure if I can do something like change.after.updateThisField = true
. That would be the simplest, but if that’s possible then what about the below? Would this work?
export const onRespondedToFriendRequest = functions.firestore
.document("users/{userDocID}/notifications/{notifID}")
.onUpdate(async (change, context) => {
//...rest of code
//Update one of the fields
await fs
.collection("users")
.doc(uid)
.collection("notifications")
.doc(change.after.id)
.update({
updateThisField: false
});
});
2
Answers
All values passed to your Cloud Function are immutable. If you want to further update the document in the database, you’ll indeed have to trigger another write action.
If the field you want to update is in the document that triggered the Cloud Function (in the code you shared that does not seem to be the case), you can reference that document from
change.before.ref
(orchange.after.ref
) and so update it with:There is a conceptual problem in the question.
change.after.ref.update({...})
. That is an endless loop. Do you really need this?In the code example you have a valid idea, where the subscription points to one path
"users/{userDocID}/notifications/{notifID}"
(notifications
subcollection), and then you update another subcollection (friends
) at"users/{userDocID}/friends/{change.after.id}"
, which looks absolutely fine.