Reputation: 89
In my web app, I want to create a classroom and add the data to my firebase database.
var fbclass = firebase.database().ref().child('Classes');
function classcreation(q) {
var usuid = generateId();
var myClasses={};
myClasses.TheClass = document.getElementById('classroomName').value;
myClasses.Teacher = user.displayName;
myClasses.TeacherEmail = user.email;
myClasses.ClassID = usuid;
fbclass.child(user.uid).set(myClasses);
}
function generateId(){
return 'xxxx-xxxx-xxxx'.replace(/[x]/g, function(){
return (Math.random() * 9 | 0 ).toString();
})
}
After submitting the button it will then store the data to the firebase
but the problem is, if I create another classroom with the same user, it will just update the TheClass[classname] and not create another classroom.
What's wrong with my code? What did I miss?
Upvotes: 0
Views: 64
Reputation: 4537
Here are a few pointers that'll be handy.
All keys are unique. You cannot have two indices of same key. Having said that, you are assigning a key as user.uid
which will always be the same. Essentially, you are updating the value present at the key.
Here, I am assuming you want to make keys based on the uid of the user using the database. So, using set
will only store your data, which means if you give it a new uid, it'll wipe off the data in your Classes
key and set it with your new user.uid
key that you have provided. If you want to append the new key, you'll need ti use the method update
instead of set. It'll update your Classes
key with the new user.uid
key which means that you'll appending data to your Classes
object.
Something on the lines of - fbclass.child(newUserID).update(myClasses);
Hope it helps :))
Upvotes: 0
Reputation: 83058
By using the set()
method you are writing the data at the fbclass.child(user.uid)
location (i.e. reference), see the doc.
Since your location is based on user.uid
you are using the same location again and again for a given user: hence the overwrite you encounter (since set()
"overwrites any data at this location and all child locations").
You should generate a unique key, each time you write a new classroom for the same user. For that you should use the push()
method (doc) which "generates a new child location using a unique key", as follows:
var newClassroomRef = fbclass.child(user.uid).push(
{
'Class_Id': '....',
'Teacher': '....'
}
);
The following would also work:
var newClassroomRef = fbclass.child(user.uid).push();
newClassroomRef.set({
'Class_Id': '....',
'Teacher': '....'
});
Note that this will create an extra level in your node tree, under the user.uid
node;
- Classes
- yo9HQ....... <- user.uid
- 6trQEd....... <- classroom uid
- Teacher: .....
- .....: .....
- PKH6fd....... <- classroom uid
- Teacher: .....
- .....: .....
Upvotes: 1