Home > Net >  How Can I Get Parent Document's Id on Firebase Functions
How Can I Get Parent Document's Id on Firebase Functions

Time:06-25

There is doc document in details collection, and it is child of {id} document in col collection.

What I want to do is, when user changes fields in col/{id}/details/doc, I wanna update fields in col/{id}.

exports.onChanged = functions.firestore
    .document('col/{id}/details/doc')
    .onWrite((change, context) => {

     .....

However, I don't know how to get {id} in JavaScript.

Is there way to get id as String?

CodePudding user response:

You might be able to receive the {id} of the document by calling the .parent method. In your case it might be two parents up, since the first parent is the collection.

So to access the {id} of the document would be:

change.after.ref.parent.parent.id

Hope it helped

CodePudding user response:

You can use the context object to get values of all wildcards in your path as shown below:

exports.onChanged = functions.firestore
    .document('col/{id}/details/doc')
    .onWrite((change, context) => {
      console.log(context.params.id);
    })
  • Related