【问题标题】:How to loop "pushing" to Firebase database using cloud functions如何使用云功能循环“推送”到 Firebase 数据库
【发布时间】:2018-11-14 04:17:52
【问题描述】:

我需要在我的数据库中添加 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;

在我的数据库中应该是这样的:

  • 学生桌

    • 罗伯特

      • 0 {日期:2018 年 11 月 13 日,班级:“高中”}
      • 1 {日期:2018 年 11 月 13 日,班级:“高中”}
      • 2 {日期:2018 年 11 月 13 日,班级:“高中”}

我是云函数(和 js)的新手,您能帮忙吗?

【问题讨论】:

  • 这是非法语法:new Dictionary&lt;string, object&gt;(); 如果您是 JavaScript 新手,Cloud Functions 并不是学习它的最佳方式。我建议先阅读Firebase documentation 和/或阅读Firebase codelab。它们涵盖了许多基本的 JavaScript、Web 和 Firebase 交互。您还可以在本地 Node.js 进程中使用 Admin SDK,该进程可以使用本地调试器进行调试。完成这些之后,您将能够更好地为 Cloud Functions 编写代码。
  • 谢谢,我不是那么新……我通常用 C++/Java 编程,并且我知道 js 基础知识,这对于我的需要并没有什么不同。我的问题是关于循环和对服务器的特定函数调用以及我需要的示例。这就是为什么我没有添加我现在看到的你添加的 node.js 标记

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


【解决方案1】:

我已经编辑了代码并使用了 async await 以使其更具可读性。有很多 JS 语法问题。我建议使用 typescript firebase 函数模板并使用 visual studio code 作为编辑器,它会为您提供 IntelliSense。此外,您还需要在顶部添加身份验证检查,以确保只有某些人可以调用该函数。

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

【讨论】:

  • 感谢 auth 检查 - 检查 'context.auth!=null' 是否足够?还是我需要连接到我的数据库并检查 context.auth.uid 是否存在?
  • 这真的取决于您是否希望所有经过身份验证的用户都能够执行此操作。如果没有,那么您需要检查您的数据库以获取允许的用户 ID 列表或其他内容。许多方法可以满足您的需求
猜你喜欢
  • 2019-09-20
  • 1970-01-01
  • 2019-12-18
  • 1970-01-01
  • 2017-10-26
  • 2018-06-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
相关资源
最近更新 更多