如何使用云功能循环“推送”到Firebase数据库

时间:2018-11-14 04:17:52

标签: node.js firebase firebase-realtime-database google-cloud-functions

我需要将3名学生的列表添加到1名老师的列表中(并假设尚不存在)。还应将字典返回给客户端。我正在使用云功能。这是我的主意,我的应用在运行时被冻结。

exports.addNewStudents = functions.https.onCall((data, context) => {
const totalStudent = data.total; //"3"
const teacher = data.teacher //"Robert"
var studentListToReturn = new Dictionary<string, object>(); 

for (int i=0; i<totalStudent,i++ )
{   // 'i' is going to be the student's ID and I use it in the path:
return admin.database().ref('studentsTable/teacher/'+i).push({

   date: Date();,
   class: "Highschool",
   }).then(() => {
  studentListToReturn[i]=i ;
  })

 return studentListToReturn;

在我的数据库上看起来应该像这样:

  • studentsTable

    • 罗伯特

      • 0 {date:11/13/2018,class:“ Highschool”}
      • 1 {date:11/13/2018,class:“ Highschool”}
      • 2 {date:11/13/2018,class:“ Highschool”}

我是云功能(和js)的新手,请您帮忙?

1 个答案:

答案 0 :(得分:2)

我已经编辑了代码,并使用了异步等待以使其更具可读性。 JS语法有很多问题。我建议使用打字稿Firebase函数模板,并使用visual studio code作为编辑器,这将为您提供IntelliSense。另外,您还需要在顶部添加一个auth检查,以确保只有某些人可以调用该函数。

exports.addNewStudents = functions.https.onCall(async (data, context) => {
    // Need to add in an auth check to make sure they have permission to do the below

    const totalStudent = data.total; //"3"
    const teacher = data.teacher //"Robert"
    const studentListToReturn: Array<any> = [];

    for (let i = 0; i < totalStudent; i++ ) {   // 'i' is going to be the student's ID and I use it in the path:
        const student: any = {
            studentId: i,
            date: Date(),
            class: "Highschool"
        }
        await admin.database().ref(`studentsTable/${teacher}/${i}`).set(student)
        studentListToReturn.push(student);
    }
    return studentListToReturn;
});