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

Time:06-04

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?

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()
    });
  }
}

CodePudding user response:

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(),
    });
}

CodePudding user response:

Adding to @Dharamaj 's answer,

As per his suggestion

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); 

needs to be replaced with:

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