Reputation: 865
I have a firebase realtime database and this this the structure of it:
you can see there is only one user with "hgjfj" userName and I want to add another users in same queue object of each barber using react native
this is the function of adding data:
NewBooking() {
var queue = { userName: 'gfdgdfg', userPhone: 54535 }
firebase.database().ref('Barbers/').push({
queue: queue
}).then((data) => {
//success callback
console.log('data ', data)
}).catch((error) => {
//error callback
console.log('error ', error)
})
}
is there a way to get the generated id by firebase like get the LWC312750NY35f3YKEL and push new user on the queue of that id
Upvotes: 0
Views: 3024
Reputation: 598765
Your current queue
is not a queue at all, but a single object with a single pair of properties. If you want to store a list of objects for each barber, then queue
should be a collection.
To add an such an object to each barber's queue, you will first need to read all barbers, then loop over the results, and finally add the object to each queue.
Something like this:
var newItem = { userName: 'gfdgdfg', userPhone: 54535 }
firebase.database().ref('Barbers').once('value').then(function(snapshot) {
snapshot.forEach(function(barberSnapshot) {
barberSnapshot.child('queue').ref.push(newItem);
});
});
If you know the ID of the barber whose queue you want to add it to, the code can be a lot simpler:
var newItem = { userName: 'gfdgdfg', userPhone: 54535 }
firebase.database().ref('Barbers/UIDofBarber/queue').push(newItem);
If you want to clear out the queue for each barber, to get rid of the faulty object you have in there now:
firebase.database().ref('Barbers').once('value').then(function(snapshot) {
snapshot.forEach(function(barberSnapshot) {
barberSnapshot.child('queue').ref.remove();
});
});
By the way, you're violating one of the recommendations from the Firebase documentation, which is to keep your data structure flat. Right now the code above needs to read both the metadata about each barber and the queue, while it really only needs to access the queue. I recommend creating to top-level collections: one for the metadata about each barber, and one for their queue:
barbers
barberUID1: { ... }
barberUID2: { ... }
queues
barberUID1: {
queuePushID11: { ... }
queuePushID12: { ... }
}
barberUID2: {
queuePushID21: { ... }
queuePushID22: { ... }
}
Upvotes: 3