Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to separately define and pass a collection name to a Firebase Cloud Function?

I have the following cloud function which creates a doc in a ‘student_history’ collection for every new doc creation in ‘students’ collection:

document("students/{student_id}").onCreate(
  async (snap, context) =>   {
    const values = snap.data();
    console.log(values);
    console.log(typeof values);
    return db.collection("student_history").add({...values, createdAt:FieldValue.serverTimestamp()});
  });

I wanted to generalise this for 2 other collections. Something like this:

export const onStudentCreated = functions.firestore.document('/students/{id}').onCreate(onDocCreated);
export const onBatchCreated = functions.firestore.document('/batches/{id}').onCreate(onDocCreated);
export const onTeacherCreated = functions.firestore.document('/teachers/{id}').onCreate(onDocCreated);

My question is, how can I have my onDocCreated function receive a collection name (eg, students, batches or teachers) and make an entry to a corresponding students_history, batches_history or teachers_history?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

async function onDocCreated() {
  async (snap, context) => {
    const values = snap.data();
    console.log(values);
    console.log(typeof values);
    return db.collection("NAMEOFTHECOLLECTION_history").add({
      ...values,
      createdAt: FieldValue.serverTimestamp()
    });
  }
}

>Solution :

First, you’ll need to pass take the snap and context params in onDocCreated() function itself. The snap is a QueryDocumentSnapshot so you can use get collection ID from the parent property as shown below:

async function onDocCreated(snap, context) {
    const values = snap.data();
    console.log(values);
   
    const collectionName = snap.ref.parent.id; 
    console.log("Collection Name:", collectionName)
   
    return db.collection(`${collectionName}_history`).add({
        ...values,
        createdAt: admin.firestore.FieldValue.serverTimestamp(),
    });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading