in Firebase DB get children value by ordering childByValue - javascript

I have Firebase database managing following structure.
-DATA
-New
-CONTENTS
-animals_animal1: 1
-foods_food10: 4
-foods_food6: 5
-girls_girl1: 2
-girls_girl5: 3
I want to get children's value by using orderByValue() as 1,2,3,4,5 manner using snaps.forEach in JavaScript. My code as follows.
exports.handleAddNewContentAndAddToNewEvent = functions.database.ref('/CONTENT_MANAGEMENT/DATA/CONTENTS/{contentId}')
.onWrite(event => {
// Only edit data when it is first created.
if (event.data.previous.exists()) {
return;
}
// Exit when the data is deleted.
if (!event.data.exists()) {
return;
}
var newContentsRef = event.data.ref.parent.parent.child('PACKS/New/CONTENTS');
return Promise.all([
newContentsRef.orderByValue().once('value')
]).then(function(snaps) {
snaps.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
console.log('loaded', childKey);
// ...
});
});
});
However, I failed to get intended solution. How to get solution what I need?
Structure

Related

Update ONLY some fields of an object in IndexedDB

For example:
object1(1) = {
name: 'Rhodok Sergeant',
speciality: 'Hand to hand battle'
}
then I want to update only the speciality field, into:
object1(1) = {
name: 'Rhodok Sergeant',
speciality: 'Long range battle'
}
Thank you.
This is possible using following steps -
fetch the item first using idbcursor
update that item
call cursor.update to store updated data in indexedb.
An example code is -
const transaction = db.transaction(['rushAlbumList'], 'readwrite');
const objectStore = transaction.objectStore('rushAlbumList');
objectStore.openCursor().onsuccess = function(event) {
const cursor = event.target.result;
if (cursor) {
if (cursor.value.albumTitle === 'A farewell to kings') {
const updateData = cursor.value;
updateData.year = 2050;
const request = cursor.update(updateData);
request.onsuccess = function() {
console.log('data updated');
};
};
cursor.continue();
}
};
Check out this link for more info - https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/update
Note:- In above code, i am looping through all records which is not efficient in case you want to fetch the particular record based on some condition. So you can use idbKeyRange or some other idb query alternative for this.
you cannot do partial updates, you can only overwrite an entire object
read the object in from memory, change it, and then write it back

Need help on calling datas from firebase html

Firebase example:
Users:
User1
A
123
234
345
B
C
Above is the firebase data.
I wanted to call all the data under User1, A. Which means "123", "234", "345" should be the output for my table. I also wanted to display them to be displayed in a table I have in my html file using javascript. Can anyone advise? I am new to firebase and am confused with the other guides online.
Should I create a table using javascript or keep my table at html file?
Thank you for advise and help.
For Real Time Database try this:
firebase.database().ref('/User1/A').once('value').then(function(snapshot) {
let items = snapshot.val();
items.forEach( (v) => writeData(v) );
});
const writeData = (value) => {
let el = document.querySelector('p');
el.innerHTML = value;
document.appendChild(el);
}
By doing the following, in JavaScript you will get all the children of the User1/A node:
var ref = firebase.database().ref('User1/A');
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
console.log(childKey);
var childData = childSnapshot.val();
console.log(childData);
//....
});
});
From there you can populate your HTML table

Firebase issue, I need to take out values from first two nodes

I try to achieve the following: When count is changed to "2" I need the function to push the JSON, named "updates", to the specific place in database, and take names from PlayerQueue node (0:"Mik", 1:"Bg" etc.) and put it into the database as "id". So the thing is that I need it to take first two nodes (0 and 1 in this case) and take names out of it (Mik and Bg) and put them in the database as id1 and id2 (in this database I have only one id value but I will add it later), the issue is that I can't figure out how to take out names from the first two nodes.
My database:
And here is my code
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import { resolve } from 'url';
//Game/queue/{queueId}/PlayerCount
admin.initializeApp(functions.config().firebase);
exports.createGame = functions.database.ref('Game/queue/PlayerCount').onUpdate((change, context) => {
const ref1 = admin.database().ref('/Game/queue/PlayerQueue').limitToFirst(1);
var tmp:String = 'esh';
ref1.once("value")
.then(result => {
tmp = result.val();
console.log(tmp)
var updates = {};
updates['id'] = tmp
updates['visible'] = {
place: 'a1',
sign: 'rock'
};
const after = change.after.val();
if(after.count == 2){
return admin.database().ref('/Game/allGames').push(updates);
}
return null
}).catch(reason => {
console.log(reason)
});
return null;
});
Since you're looking for the first two child nodes in the queue, you should order by their ID and then limit to getting 2 children:
const query = admin.database().ref('/Game/queue/PlayerQueue').orderByKey().limitToFirst(2);
Then you can listen for the value:
query.once("value").then(snapshot => {
snapshot.forEach(child => {
console.log(child.key+": "+child.val());
});
});
The above purely solves the "getting the first two child nodes".
Update: to get the two children into separate variables, you can do something like this:
query.once("value").then(snapshot => {
var first, second;
snapshot.forEach(child => {
console.log(child.key+": "+child.val());
if (!first) {
first = child.val();
}
else if (!second) {
second = child.val();
}
});
if (first && second) {
// TODO: do something with first and second
}
});
Use Firestore unless you have a valid reason to use the Realtime Database.
See Cloud Firestore triggers documentation on how to take action .onUpdate to qty 2. See documentation example below
exports.updateUser = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {
// Get an object representing the document
// e.g. {'name': 'Marie', 'age': 66}
const newValue = change.after.data();
// ...or the previous value before this update
const previousValue = change.before.data();
// access a particular field as you would any JS property
const name = newValue.name;
// perform desired operations ...
});

Retrieve Keys and elements of Array Firebase Database

I'm working with Firebase realtime database and I want to retrieve an array data:
Data:
And my function:
function traerUsuarios(firebase)
{
var ref = firebase.database().ref().child('/Usuario');
console.log(ref)
ref.once('value', function (snap) {
snap.forEach(function (item) {
var itemVal = item.val();
console.log(itemVal);
});
});
}
But the result:
Show me object but no de for of the items
What im doing wrong?
Each item in your for loop are the children of Usario. Each of these children (from your picture 056BN.., CQL.., and E4ll) have an object as their value (hence why they have a + next to them in the database).
So when you say item.val() you're getting the value of each one of those children, which is their corresponding object (The data you see when you click the + in the database.
Thanks to #MarksCode , I fixed the function with data refs:
function traerUsuarios(firebase) { var key;
var starCountRef;
var usuarios=new Array();
// var ref = firebase.database().ref().child('/Usuario');
var query = firebase.database().ref("/Usuario").orderByKey();
query.once("value")
.then(function (snapshot) {
snapshot.forEach(function (childSnapshot) {
// key will be "ada" the first time and "alan" the second time
key = childSnapshot.key;
starCountRef = firebase.database().ref("/Usuario/"+key);
starCountRef.on('value', function (snapshot) {
console.log(snapshot.val());
usuarios.push([key,snapshot.val()]);
});
});
}); }
And the result show me the values:

Saving array of data to Firebase with Javascript/NodeJs

I need to save data to the database but at a certain index. I tried pulling the data down with
var people = [];
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var ID = childSnapshot.key;
childSnapshot.forEach(function(lastSnapshot) {
var qr = lastSnapshot.val();
people.push({[ID]: qr});
return true;
});
});
My firebase structure:
people: {
jake: "231",
jessica: "412",
rachel: "112"
}
Then I splice the list and add someone at a certain index:
index = 1; // add person after jessica
people.splice(index, 0, person);
I want to sync this back up to Firebase but set and update don't allow a format like this.
How can I do this? Thanks!

Categories