How to get cloud function onCreate trigger doc id

Viewed 6625

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?

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.

Related