Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get cloud function onCreate trigger doc id

I want to get the id of the document that trigger the oncreate function but i tried snap.params.id like below but i am getting undefined.

When i console log this projectId, i am getting undefined and sometimes throws error and i am using version "firebase-admin": "~5.12.1", "firebase-functions": "^1.0.3"

    exports.created = functions.firestore.document('projects/{projectId}')
      .onCreate(snap => {
    
        const projectId = snap.params.id;
 
        const project = snap.data();
        const notification = {
          title: `${project.title}`,
          projectId: `${projectId}`
        }
    
    });

So how do i get the document id?

like image 571
R.Ovie Avatar asked Dec 17 '18 11:12

R.Ovie


People also ask

Which type of trigger is bound while creating cloud function in the lab?

Triggers supported in Cloud Functions (2nd gen) All event-driven functions in Cloud Functions (2nd gen) use Eventarc for event delivery. In Cloud Functions (2nd gen), Pub/Sub triggers and Cloud Storage triggers are implemented as particular types of Eventarc triggers.

What is the path to the cloud firestore collection where the extension should monitor for changes?

Collection Path: What is the path to the Cloud Firestore collection where the extension should monitor for changes? For subcollection, the syntax is parent_collection/{parentId}/target_collection . (please note, there is not depublication process on subcollections).


1 Answers

Since you use a Cloud Functions version >= 1.0, events for onCreate have two parameters as shown below, and you should use context.params.

exports.created = functions.firestore.document('projects/{projectId}')
   .onCreate((snap, context) => {

       const projectId = context.params.projectId;

       const project = snap.data();

       //......

   });

See this doc item for more detail.

like image 143
Renaud Tarnec Avatar answered Sep 22 '22 08:09

Renaud Tarnec