Retrieve data from specific node in Firebase database using javascript - javascript

firebase snippit
Hello all. I am creating a web app that pulls from a firebase realtime database I have created. Using javascript I would like to pull the data from a specific node (i.e. "8").
I will then use the keys and values from the node in the web app.
What js/firebase code do I need to pull data from any specific node?
Below is the code we have tried. Long term goal is to pull data from a random node, but right now I just to find out how to pull from a specific node. Since the nodes are always going to be a number from 0-49, I don't need to use "length of array" functions when randomizing. I will use "Math.floor(Math.random() * 49" to give me a random number which I can pass into the index value for the node when I figure out how to access one specifically.
ref = firebase.database().ref('articles/');
function setupObservers() {
ref.on('value',function(snapshot){
console.log(snapshot.val())
let articleArray = []
for(key in snapshot.val()) {
let articleKeys = snapshot.val()[key]
articleArray.push(articleKeys)
}
randomArticle(articleArray)
})
}
function randomArticle(articleArray) {
let random = articleArray[Math.floor(Math.random() * articleArray.length)]
console.log(random)
}
setupObservers()
Thanks in advance!!

To read the value from a specific child node of which you know the key, you simply do:
ref = firebase.database().ref('articles');
ref.child("8").on('value',function(snapshot){
console.log(snapshot.val())
});

Related

How to do firebase multipath push?

I have seen multipath update example. But before updating any data i have to push it at first place for which i was wondering if there is something called as multipath push?
I want to simultaneously push data under different set of nodes.
eg: Firebase scheme
-Examinations
- pushIdLk12203425
- pushIdML0124245
-RightChoices
- pushIdLk12203425
- pushIdML0124245
-Questions
- pushIdLk12203425
- pushIdML0124245
When i push value under examination node, same values or different values as per my backend architecture have to be pushed under RightChoices and Questions Node. Right now i am doing this using .then callback approach.
I push data under Examinations and then in its .then callback i push in RightChoice and Questions node.
But my concern is what if user closes the app and data just reaches Examinations node and never reaches RightChoices and Questions Node.
I am trying to figure out a better way of having data consistency.
Thanks.
Note: RightChoices and Questions are kept under different nodes for having a better security architecture and i cannot change the schema.
Would be grateful if somebody can help me out. Thanks.
I think you are looking for .update()
Have a look here: https://firebase.google.com/docs/database/web/read-and-write#update_specific_fields:
function writeMultipath(pushID1, pushID2) {
var data = {
id1: pushID1,
id2: pushID2
};
// Write the new data simultaneously to your DB-locations
var updates = {};
updates['/Examinations/'] = data;
updates['/RightChoices/'] = data;
updates['/Questions/'] = data;
return firebase.database().ref().update(updates);
}

Write pre-determined node id when pushing to Firebase array

This question has been asked before, but none of the solutions provided seem to help my problem:
I have an array of data on Firebase, that I loop through to generate content in my app, using a "for" loop and therefore an index value. This works fine with the predetermined sets of data, as the IDs are simple array numerics but when a user adds some new data, which is added to the array with push(), firebase creates a unique node key (such as -KyWRU7RRCE_V1w_OiZx) for the new set of data which for some reason prevents my loop from working (no errors shown in console).
If I go to firebase and manually ensure that the new set of data has a numeric value, loop starts working again. How do I make it so that when the user pushes new data to the array, the key being generated is numeric? I tried this:
// Push new routine to Firebase.
var firebaseRef = firebase.database().ref();
var createdExercise = JSON.parse(localStorage.newRoutine);
$("#save").click(function()
{
firebaseRef.child("workouts").key(some_indexed_value).push(createdExercise);
});
but the console returns the following error: Uncaught TypeError: firebaseRef.child(...).key is not a function.
In case it is useful, here is the loop I am using:
// Initialize Firebase.
firebase.initializeApp(config);
// Reference data.
var dbRef = firebase.database().ref().child("workouts");
// Sync with Firebase in real time.
dbRef.on("value", snap =>
{
var workouts = snap.val();
for (var i = 0; i < workouts.length; i++)
{
var routine = workouts[i].title;
var time = 3;
var exercises = workouts[i].exercises;
var icons;
$("#cardList").append(createCards(routine));
}
});
And a pic of my JSON data on Firebase:
Answer to your question is using .set() instead of .push() like this
firebaseRef.child("workouts").child(some_indexed_value).set(createdExercise);
this will create a node under workouts with your custom key.
but it is recommended to use push keys and use forEach() method to get the result than using for loop

Firebase Cloud Function database snapShot

I am trying to write a Firebase Cloud Function that takes all the users from my database and edits values within them. However, in order to do that I need a quick way for the code in my Cloud function to receive all of the user-ids from the database. For now, I have the function print the data it gets from the database so I know what I am working with.
The result is this:
{"WNGOuQqZhZSo5UFovgmgEAVX3Gz1":{"displayName":"jack","email":"test2#gmail.com"},"aRaZVJorkYNwCSzAbMkNJiGwzJm2":{"displayName":"testing","email":"testing#gmail.com"}}
I just need the two userIds instead.
This is the part of database I am working with:
This is the code:
If anyone knows what I need to change I would really appreciate it! Thanks!
I think you need to have a for - in loop over value. Below is the pseudocode -
var value = snapShot.val();
let namesArray = [];
for (var key in value) {
if (value.hasOwnProperty(key)) {
namesArray.push(key);
}
}
As with what jaibatrik said, you need to iterate over your objects.
You can't get the key without fetching the whole object.
In addition to running a for loop you can run a forEach over the snapshot.
const uids = [];
snapShot.forEach(single => {
uids.push(single.key);
});
The other option is to get all the keys from the snapShot.val() object.
const value = snapShot.val();
const uids = Object.keys(value);
Both ways are effectivly the same thing, just a preference on which way you prefer to do things

Algolia browse function returning max 1000 records using Javascript

I am using algolia javascript api for retrieving all records in my index using browse function, but still it is returning 1000 records. Here is my code:
function load_location_list(){
var client = algoliasearch('ID', 'KEY');
var index_name = "locations_new";
var attribute_list = "*";
var index = client.initIndex(index_name);
index.browse({
"attributesToRetrieve": attribute_list,
}).then(function search_Success(response) {
console.log(response);
});
}
Actually, browse doesn't return more than 1000 elements at the first call. However, the response contains a cursor that you can use to access the next elements with the browseFrom function.
However, the previous method is kind of manual. You probably want to use the browseAll function instead which lets you access all the elements sequentially.
You can find more informations about all the browse* functions in the README of the JS client (also available in the Algolia documentation).

How to create an array and store in local storage using json

Hi guys so i have a form which takes in data like item name, code etc, so when i press the enter button...iv used json stringify and get an alert of what is stored in the local storage. However when i click reset and create a new item it just shows the new item, is there anyway i could store all my items created in local storage...? this is part of my coding. Im a beginner so please excuse if the question is too simple
Thanks
$('#myBox #EnterButton').click(function() {
ItemData = {
'ItemCode' : $('#ItemCode').val(),
'ItemName' : $('#ItemName').val()
};
localStorage.ItemData=JSON.stringify(ItemData);
$('#myBox').slideUp();
});
...
$('#myBox2 #EnterButton').click(function() {
if (localStorage.ItemData) {
alert(localStorage.ItemData);
ItemData = JSON.parse(localStorage.ItemData);
}
if (ItemData.ItemCode) {
$('#myBox #ItemCode').val(ItemData.ItemCode);
}
if (ItemData.ItemName) {
$('#myBox #ItemName').val(ItemData.ItemName);
}
})
and i have declared itemdata as a public variable. Hope its clear. TIA
You have to organize the way ÿou are using localStorage (a getter/setter class might help with maintenance). From your code above, it seems you are always overriding localStorage.ItemData with the values just inserted.
The solution would be for localStorage.Items to be an array and whenever you insert in that array, iterate over it to see if it's not already added (based on itemCode for instance) and override or insert a new item.
I presume this is enough for playing around. A more advanced concept than localStorage and used for slightly different purpuses would be pouchdb - websql in the browser.
Sounds like if you want multiple items to be stored, you should be using an array of itemData objects. You'll then have to parse this (array), and use something like Array.push(newItem) then stringify it again before saving it.
var allItems = localStorage.getItem('ItemData');
if(allItems == null) {
localStorage.setItem('ItemData', JSON.stringify([ItemData]));
} else {
allItems = JSON.parse(allItems);
allItems.push(ItemData);
localStorage.setItem('ItemData', JSON.stringify(allItems));
}

Categories