Reputation: 1
I'm currently working on a project where Students should have a unique(preferably auto-incremented) Id(Student number) on Firebase real-time Database whereas the "Student ID" is the child of the generated UID of Firebase and the generated UID is the child of "Students" collection. Can you please help me with this, it would be a big help. Thanks!
This is the firebase database. "studnum" should be auto-incrementend(unique)
Upvotes: 0
Views: 323
Reputation: 50850
You would have to store the last student number somewhere else in the database. Maybe something like this will work:
root
|-Students
|-sysData
|-lastStudentNum
So let's say we keep the default value of lastStudentNum as 1000. Then whenever you create a new student, also make this update operation.
const studentCountRef = admin.database().ref("/sysData")
studentCountRef.update(admin.database.ServerValue.increment(1));
Do note that this uses Firebase Admin SDK which means you should run this in a secure environment - either your servers or Cloud Functions. You can increment things from client but as this is sensitive so you shouldn't rely on client side for incrementing this.
A cloud function for this may be something like:
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
});
Using a transaction maybe a good idea just in case a lot students can be added simultaneously.
If your app allows students to sign up instead of someone adding student accounts, then you can use Firebase Auth Triggers which will run a cloud function whenever a new account is created and you can assign new students an ID that way.
Upvotes: 0