Firebase cloud functions: How to get the reference to the document with wildcard notation?

Viewed 1330

Here are what I am trying to do with Firebase cloud functions:

  1. Listen to change in one of the documents under 'public_posts' collection.

  2. Tell if the change is in the 'public' field from true to false

  3. If true, delete the document that triggered the function

For steps 1&2, the code is straightforward, but I don't know the syntax for step 3. What would be the way to get the reference of the document that triggered the function? That is, I'd like to know what would be the code in question for the empty line below:

exports.checkPrivate = functions.firestore
.document('public_posts/{postid}').onUpdate((change,context)=>{
     const data=change.after.data();
     if (data.public===false){
         //get the reference of the trigger document and delete it 
     }
     else {
         return null;
     }
});

Any advice? Thanks!

2 Answers

As explained in the doc:

For onWrite and onUpdate events, the change parameter has before and after fields. Each of these is a DataSnapshot.

So, you can do as follows:

exports.checkPrivate = functions.firestore
.document('public_posts/{postid}').onUpdate((change, context)=>{
     const data=change.after.data();
     if (!data.public) { //Note the additional change here
 
         const docRef = change.after.ref;
         return docRef.delete();

     }
     else {
         return null;
     }
});

Update following Karolina Hagegård comment below: If you want to get the value of the postid wildcard, you need to use the context object like: context.params.postid.

Strictly speaking you get the document id, not its DocumentReference. Of course, based on this value, you can rebuild the DocumentReference with admin.firestore().doc(`public_posts/${postid}`); which will give the same object than change.after.ref.

Related