【问题标题】:Auto-increment child of child in Firebase DatabaseFirebase 数据库中子项的自动递增子项
【发布时间】:2021-05-18 09:39:00
【问题描述】:
我目前正在开展一个项目,其中学生应该在 Firebase 实时数据库上拥有一个唯一(最好是自动递增的)ID(学生编号),而“学生 ID”是 Firebase 生成的 UID 的子代,并且生成的 UID 是“学生”集合的孩子。你能帮我解决这个问题吗,这将是一个很大的帮助。谢谢!
这是 firebase 数据库。 “studnum”应该是自动递增的(唯一)
【问题讨论】:
标签:
firebase
firebase-realtime-database
【解决方案1】:
您必须将最后一个学号存储在数据库中的其他位置。也许这样的事情会起作用:
root
|-Students
|-sysData
|-lastStudentNum
假设我们将 lastStudentNum 的默认值保持为 1000。那么每当您创建一个新学生时,也进行此更新操作。
const studentCountRef = admin.database().ref("/sysData")
studentCountRef.update(admin.database.ServerValue.increment(1));
请注意,这使用了Firebase Admin SDK,这意味着您应该在安全的环境中运行它 - 无论是您的服务器还是 Cloud Functions。您可以从客户端增加内容,但由于这很敏感,因此您不应该依赖客户端来增加它。
为此的云函数可能类似于:
exports.addStudent = functions.https.onCall((data, context) => {
const userUid = context.auth.uid
//Check if user is allowed to add new students
//Check for last student number
//Add data in DB and increment the last student number
});
使用transaction 可能是个好主意,以防可以同时添加很多学生。
如果您的应用允许学生注册而不是其他人添加学生帐户,那么您可以使用 Firebase Auth Triggers,它会在创建新帐户时运行云功能,并且您可以通过这种方式为新学生分配一个 ID。