Accessing Firebase push() child - javascript

I'm slowly getting into Firebase but have what is probably a stupid question. If I am adding children to a reference using push(), how do I retrieve/delete them if I don't save the generated push ID?
For example, take this root:
var ref = https://myaccount.firebaseio.com/player
And if I write a new entry to /player:
var new_player= ref.push({
name:"User",
country:"United States"
})
Firebase generates a push ID for that:
https://myaccount.firebaseio.com/player/-JxgQCQsSLU0dQuwX0j-
which contains the information I pushed. Now lets say I want to retrieve or remove that player? Should I store the generated ID as a child of itself using .key() and .set()?:
//this will get -JxgQCQsSLU0dQuwX0j-
var _newPlayerKey = new_player.key();
//updates the record I just created
var update_player = ref.set({
name:"User",
country:"United States",
ref: _newPlayerKey
})
I don't see how else to access that object by it's generated ID... is there a better way to set this up?

Why are you doing that can't use the key() method, it should be adequate in almost all cases i.e.
playersRef.limit(10).on('child_added', function (snapshot) {
var player = "<p>"+ snapshot.val().name +" <button data-value='"+snapshot.key()+"'>Delete</button></p>";
$(player).appendTo($('#messagesDiv'));
});

Related

Display Firebase data appended with jquery to a table in order

I am currently trying to append data through I pull from Firebase to a table in the order of newest to oldest posts. I currently have the following setup in my code base (simplified to address issue):
var theDataRef = new Firebase('https://my-app.firebaseio.com');
theDataRef.orderByChild("timestamp").limitToLast(25).on('child_added', function (snapshot) {
var message = snapshot.val();
displaytableRow(message.name, message.text);
}
function displaytableRow(name, message) {
$("#sch").find('tbody > tr:first')
.before($("<tr><td><div>" + name + ":" + message + "</div></td></tr>"))
};
I have tried to create a table that displays newest to oldest data by using both firebase and jquery techniques but every time my data is displayed in a random order. I have a working timestamp field on every record in my data as well but even ordering by that does not solve the problem. Has anybody had any experience building this successfully?
EDIT:
The timestamp is gotten with the following code:
var timestamp = Firebase.ServerValue.TIMESTAMP;
And the database architecture is structured like so:
If you want to order your posts from newest to oldest you can do the following:
1/ Store a field in your post that is the inverse of the TimeStamp as follows:
var tDate = new Date().getTime();
var postData = {
//.....
timestampInverted: (0 - tDate),
//.....
};
2/ Query your posts ordered by this field as follows:
theDataRef.orderByChild("timestampInverted").limitToLast(25).once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
displaytableRow(childSnapshot.val().name, childSnapshot.val().text);
});
});
It is important to note that theDataRef.orderByChild("timestampInverted").limitToLast(25) returns a Query, which returns a DataSnapshot : Therefore you need to use snapshot.forEach() (see doc here) to iterate over the different posts items.
Also note that "even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you always need to loop over the snapshot".

Firebase - For item in directory

I have some data in a directory and I want to retrieve the value of a certain object e.g. Get the value of "NVR".
Another task I need to do is have a 'for' loop to go over and get information about different questions from the following data. I would need to get the number e.g. "001" and the items inside of that subdirectory. And it would also need to go through every directory in 'questions' such as NVR or MTH.
For the first one, you can try this:
firebase.database().ref().child("unique").on('value', function(snapshot) {
var datas = snapshot.val();
var nvr=datas.NVR;
)};
For the second one try this:
firebase.database().ref().child("questions").child("NVR").on('value', function(snapshot) {
snapshot.forEach(function(child) {
var keys=child.key;
var datas = child.val();
var correcta=child.val().correctAnswer;
var num=child.val().numberOfAnswers;
//etc
});
});
the first one the snapshot will be at unique, then you will be able to retrieve the child NVR.
In the second one, you iterate inside NVR and retrieve the key using var keys=child.key;
Try something like this for going through every directory in questions and for each one getting all the questions in it :
firebase.database.ref('questions').on('value').then((snapshots) => {
//print whole questions group (nvr, mth, etc)
console.log(snapshots.val())
snapshots.forEach((snapshot) => {
//print each question in question group
console.log(snapshot.val())
})
}
Both Peter's and Egor's answers load all data under unique. Since you know the key of the item whose value you want to retrieve, you can load this more efficiently with:
firebase.database().ref("unique/NVR").on('value', function(snapshot) {
var nvr=snapshot.val();
)};

How to access firebase db sub object elements?

My firebase db structure is given below,
users
fb-user-key1
user1-details1
Tags
Tag-key1
"name":"value"
Tag-key2
"name":"value"
fb-user-key2
user1-details2
Tags
Tag-key1
"name":"value"
Tag-Key1 & user-key's are generated by firebase with push(). firebase code to access the content is,
var fbref = firebase.database().ref("users");
fbref.child("Tags").on("child_added", function(e){
var Tagobj = e.val().name;
console.log(Tagobj);
});
This one is not returning anything. I am not able to access name:value pair in the above data structure.
`
adding modified code,
firebase.database().ref("users").on("child_added",function(eā€Œā€‹) { var Tagobj = e.val().Tags; });
Output of the above code is output data structure
How to access that name value pairs?? firebase keys are issue?
Not getting, where I am wrong. Appreciate your inputs.
Since Tags is a child property of each user, then you have to read it off of each user object.
If you want all Tags for all users, assuming Tags for each user is not updated after a user is created, you can do this:
tagsPerUserId = {};
firebase.datatabs().ref('users').on('child_added', function(snap) {
tagsPerUserId[snap.key] = snap.value().Tags;
// TODO: Notify view that tagerPerUserId is updated and needs to be re-rendered
console.log(`Tags for userId ${snap.key}: ${snap.value().Tags}`);
});
This way you will also get Tags of new users when they are created, but you will not get updates to Tags of existing users.

How to get firebase id

Anyone know how to get the Firebase unique id? I've tried name(), name, key, key(). Nothing works.
I am able to see the data but I have no idea how to get the id back. I need it.
//Create new customers into firebase
function saveCustomer(email) {
firebase.database().ref('/customers').push({
email: email
});
firebase.database().ref('/customers').on("value", function(snapshot) {
console.log(snapshot.val());
console.log(snapshot.value.name());
}, function(errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
The call to push will return a Firebase reference. If you are using the Firebase 3 API, you can obtain the unique key of the pushed data from the reference's key property:
var pushedRef = firebase.database().ref('/customers').push({ email: email });
console.log(pushedRef.key);
The key for the pushed data is generated on the client - using a timestamp and random data - and is available immediately.
Calling push() will return a reference to the new data path, which you can use to get the value of its ID or set data to it.
The following code will result in the same data as the above example, but now we'll have access to the unique push ID that was generated:
// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push();
// Get the unique ID generated by push()
var postID = newPostRef.key();
Documentation.
but this method won't work when you also need the id beforehand
for example to save it in the database itself.
Firebase suggests this:
// Add a new document with a generated id.
var newCityRef = db.collection("cities").doc();
--for some reason, push() and key() didn't work for me. also in this case the reference contains the whole path. so need a different method for getting the id.
Doing this below helped to get the id from the reference and use it.
const ref = db.collection('projects').doc()
console.log(ref.id) // prints the unique id
ref.set({id: ref.id}) // sets the contents of the doc using the id
.then(() => { // fetch the doc again and show its data
ref.get().then(doc => {
console.log(doc.data()) // prints {id: "the unique id"}
})
})

How to assign a variable using firebase javascript

Reading the firebase doc this line:
database.ref('/').once('value').then(function(snapshot)
That is from a paragraph titled "Read data once" which I'm assuming reads in all the data from the database.
I'm just struggling to figure out how to assign data from the object that is returned to a variable in javascript.
What I want to do is populate a dropdown list with place names.
For instance if I have a field called Location in the db containing place names eg Sydney, Melbourne, Brisbane how would I get the data from the returned object and assign it a variable called place so I can then use the place variable to populate the html dropdown list.
You can try with this simple code -
database.ref('/').once('value').then(function(snapshot){
var list = snapshot.val();
if(list)
{
for (item in list)
{
itemIndex = item;
item = list[item];
//access your properties of the object say - item.location
}
}
});
You have to user 'child_added'
example:
var dbRef = firebase.database().ref().child('someChild');
dbRef.on('child_added', function(snap){
var res = snap.val().theValueYouNeed;
});
The code above gets the specific child in your db like this:
someChild:{
theValueYouNeed:"some value"
}
Then you can populate your list with the values.
I hope this helps!

Categories

Resources