繁体   English   中英

如何单独定义集合名称并将其传递给 Firebase Cloud Function?

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

我有以下云函数,它为“students”集合中的每个新文档创建在“student_history”集合中创建一个文档:

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

我想将其推广到其他 2 个系列。 像这样的东西:

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

我的问题是,如何让我的 onDocCreated 函数接收一个集合名称(例如,学生、批次或教师)并输入相应的学生历史、批次历史或教师历史?

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

首先,您需要在onDocCreated()函数本身中传递snapcontext参数。 snap是一个QueryDocumentSnapshot ,因此您可以使用从parent属性获取集合 ID,如下所示:

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

添加到@Dharamaj 的答案,

按照他的建议

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

需要替换为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM