Firebase Cloud Function database snapShot - javascript

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

Related

Retrieve data from specific node in Firebase database using 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())
});

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 how to dynamically search for a push key under a user's data

{
"foo":{
"uid":{ // user's uid
"push_key_1":{
"bar":"baz"
},
"push_key_2":{
"bar":"baz"
}
}
}
}
Given the code model above, how do I dynamically search for the push_key_1 or push_key_2 in a query?
I've tried to do :
var searKey = 'push_key_1';
db.ref('foo').orderByKey().equalTo(searKey).once('value')
.then(function(snap){
// snap.val() returns null.
}).catch();
But the snap.val() is null. Turns out orderByKey() is for sorting purposes only. Is there a way to achieve this?
It's a lot simpler than what you're trying. When you know the key of the node you want to load, you don't need a query at all:
db.ref('foo').child(searKey).once('value'....
I think it's not possible unless you restructure the database. My approach is to add another node to store the push keys.
"users_push_keys": {
"push_key_1": "uid_1",
"push_key_2": "uid_1"
}
With this, you can get the uid by retrieving the data from this node.
Hope this helps :)

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));
}

node.js/javascript/couchdb view to associative array does not seem to work

I am trying to create a webapp on a node/couchdb/windows stack but get terribly stung by what seems to be a lack of experience.
In the database, there is a view that returns all users with passwords. Based on the tutorial for a blog I have tried to access the view through my node code.
Whenever I investigate the structure of the users or users variable, I get an undefined object.
The call to getDatabase() has been tested elsewhere and works at least for creating new documents.
function GetUser(login)
{
var users = GetUsers();
return users[login];
}
function GetUsers() {
var db = getDatabase();
var usersByEmail = [];
db.view("accounts", "password_by_email")
.then(function (resp) {
resp.rows.forEach(function (x) { usersByEmail[x.key] = x.value});
});
//usersByEmail['test'] = 'test';
return usersByEmail;
}
I am aware that both the use of non-hashed passwords as well as reading all users from the database is prohibitive in the final product - just in case anyone wanted to comment on that.
In case something is wrong with the way I access the view: I am using a design document called '_design/accounts' with the view name 'password_by_email'.
Your call to db.view is asynchronous, so when you hit return usersByEmail the object hasn't yet been populated. You simply can't return values from async code; you need to have it make a callback that will execute the code that relies on the result.

Categories