I don't get the values from my firebase database - javascript

I am trying to retrieve data from my database and my code doesn't return the desired content. It's structure is this:
And this is my code:
firebase.database().ref('proiecte/').once('value').then(function(snapshot){
console.log(snapshot.val().nume)
});
I would expect for my console to return "ROSE" but it returns "undefined". Maybe it helps so I'm mentioning this too: if I run console.log(snapshot.val()) it returns this:
{…}
1544696773350: Object { descriere: "Proiectul este dedicat tinerilor!", nume: "ROSE" }
<prototype>: Object { … }
So, I'm sure that the database is correctly made just that I'm not using the right format for retrieving data. Can anyone tell me where I am wrong please?

To solve this issue, try the following:
firebase.database().ref('proiecte/').once('value').then(function(snapshot){
snapshot.forEach(function(childSnapshot){
let name = childSnapshot.val().nume;
let desc = childSnapshot.val().descriere;
});
});
Here your snapshot is at node proiecte, then you loop using forEach and retrieve the data that's under the random id, so you will be able to retrieve nume and descriere.

I managed to solve this issue!
What I did was to replace ".once('value').then(function(snapshot)" with ".on('child_added', function(snapshot)".

Related

axios didn't return data with matching query string of parameter object but returns all the data in vanila JS

i have an api endpoint https://countriesnode.herokuapp.com/v1/countries.
Now i am fetching all the countries by
axios.get('https://countriesnode.herokuapp.com/v1/countries')
it returns successfully. Besides I want to fetch single countries with the country code like 'BB' .and i am trying with params and my object is like below
axios.get('https://countriesnode.herokuapp.com/v1/countries',
{
params: {
code: codeId
}
but it returns all the data like above rather than showing a single country with the following code. I also want to extract only the currency and area code. I wanted to try like this, don't know it gonna work or not.
.then(axios.spread((object) => {
console.log('Currency: ', object.data.currency);
console.log('Area code: ', object.data.emojiU);
}));
please someone help me... It took me almose the hole day for this but not able to success.
As per your comment, if you want to get the data of a specific country, you only have to append the country code id to the URL:
const codeId = 'BB';
axios.get(`https://countriesnode.herokuapp.com/v1/countries/${codeId}`)
Would give you the data for Barbados.
If you want to access the currency attribute you can do so with the code:
const codeId = 'BB';
axios.get(`https://countriesnode.herokuapp.com/v1/countries/${codeId}`).then(function(response) {
const currency = response.data.currency;
});

Problem with retrieving data from firebase database

I have a problem retrieveing data from firebase database. The data structure is like this:
posts:{
(Random key):{
post:{
text: "random text"
title: "title of some kind"
username: "username"
}
}
}
and the code I tried to retrieve text is:
database.ref("posts").orderByChild("post").on('value', function(snapshot){
console.log(snapshot.val().text);
})
I am new to this firebase thing, so i am sorry if it's a stupid question.
You have to change your code like this:
database.ref("posts").child(randomKey).on('value', function(snapshot){
console.log(snapshot.child("post").child("text").val());
})
Your snapshot is a DataSnapshot and it contains a child() method that is a DataSnapshot itself. To get your text field you just have to use chield("text") and get then the val().
First you can sort the result by using orderBy on any attributes on post.
For example
var sortedpost = firebase.database().ref('posts').orderByChild('post/text');
Or simply you can also use orderByKey to sort based on the document ID.
After this you can get the result you are looking for using on listener as below.
sortedpost.on('value', function(snapshot){
console.log(snapshot.val());
})

Nested orderByChild for Firebase

I am trying to get a list of race times for females in a Firebase database that I have. I may have structured the database incorrectly but I can't see why what I am doing isn't working.
I am trying to get a list of users that are female then check what the fastest time is that matches any of the female uid's. But I am stuck with joining the tables.
My database and code looks like this:
var userref = rootref.child("Users");
var raceref = rootref.child('Races');
userref.orderByChild("Gender").equalTo('Female').on("child_added", function(snapshot) {
console.log(snapshot.key);
raceref.orderByChild("uid").equalTo(snapshot.key).once("child_added", function(raceshot) {
console.log(raceshot.key);
});
});
Then the console only shows the snapshot.key not the raceshot.key:
-864646859
-305907999
If I manually put the numbers from snapshot.key in then raceshot.key does show in the console. I don't get any errors so I am confused as to why I can't use the snapshot.key for the equalTo?
The key of a snapshot is by definition a string, so your in your /Users/$id the $id values are strings. But in the /Races/$raceid/uid property you store the value as a number.
My sense is that the comparison fails on the type. If that is indeed the cause, you should be able to fix it by converting the key to a number:
userref.orderByChild("Gender").equalTo('Female').on("child_added", function(snapshot) {
console.log(snapshot.key);
raceref.orderByChild("uid").equalTo(parseInt(snapshot.key)).once("child_added", function(raceshot) {
console.log(raceshot.key);
});
});

Jquery Get array from json and see if value exists

I'm trying to write a script that retrieves data from JSON using jquery. I searched the downloaded array. How to find the value to perform any operation.
I pull out the data using getJSON and everything works. But I'm having trouble finding the search. Can anyone help me? This data from JSON:
[{"id":"10","data":"12345"},{"id":"11","data":"6666"}]
The simplest way to search through an array would be....
var data = [{"id":"10","data":"12345"},{"id":"11","data":"6666"}];
for(var row in data)
{
var item = data[row]; //This is the object {id:..., data:...}
if(item.id == ...) //Use if statement to search for data
{
//do something here when data is found
}
}

How to query Firebase data after using .push() to add data?

Here is the code for when I'm pushing the data to Firebase:
firebase.database().ref(`booklogs/${uid}/${book_id}`).push(page_id)
booklogs :
{HUMjSHxVKAPfVXzOId9zCBkGOgv1:{
book28917: {
-KYp4FdYYODDZG1FX-Pb: 1
}
}
}
My problem is when I query the data, the child node of the ${book_id} includes the push key, but I only want to get the value which is 1 and not the push key.
The code I use to query is:
var booklogs = db.ref(`booklogs/${uid}/${project}`);
booklogs.once('value')
.then((snapshot) => {
console.log(`pages viewed are ${snapshot.key}: ${snapshot.val()}`);
console.dir(snapshot.val());
}).catch((error) => {
console.log(`Error : ${error}`);
});
The data returned in the console is:
pages viewed are 2634651: [object Object]
{ '-KYp4FdYYODDZG1FX-Pb': 1 }
Any input would be much appreciated. Thanks!
If you only want the '1' and not the push key, try using .set()
firebase.database().ref(`booklogs/${uid}/${book_id}`).set(page_id)
That will get rid of the object and just give you the value that you wanted. Push automatically generates a key for every value you add, so you will always get an object back. From the Firebase docs - "For basic write operations, you can use set() to save data to a specified reference, replacing any existing data at that path."
https://firebase.google.com/docs/database/web/read-and-write

Categories

Resources