How to get only one element from an array (firebase database, nodejs) - javascript

If I use limitToLast(1), then I still get an object, with one key-value pair. To get the value, I use this code:
db.ref('/myarray').limitToLast(1).once('value').then(function(snapshot) {
var result = snapshot.val();
var lastElem;
var lastKey;
for(var i in result) {
lastElem= result[i];
lastKey = i;
break;
}
...
});
It works, but I think I do it wrong. But haven't found any better solution in the docs. How should I load only one element?
The database looks like this:

When using Firebase queries to get children, use the "child_added" event:
db.ref("/myarray")
.orderByKey() // order by chlidren's keys
.limitToLast(1) // only get the last child
.once("child_added", function(snapshot) {
var key = snapshot.key;
var val = snapshot.val();
...
});

Related

Get Key Value Given Other Key Value in FireBase

I am trying to find a way to find the value of the id given the email.
For example, If I had email2#gmail.com, It would give me the ID 108454568498950432898.
All emails are unique and there will be no repetition of emails.
This is my user tree:
Note: In the image it says email2 instead of email2#gmail.com. Ignore this
Here's my code so far:
(Code won't run obviously but it's easier to enter code using the embed)
var users;
var givenEmail = "email2#gmail.com";
var neededID;
var dataRef = firebase.database().ref('users');
dataRef.on('value', (snapshot) => {
const data = snapshot.val();
users = data;
});
var usersArray = Object.keys(users);
for(i = 0; i < usersArray.length; i++) {
if(users[i].email == givenEmail) {
neededID = i;
break;
}
}
I recommend using a query to perform the filtering on the server, instead of downloading the entire users node and filtering in your application code as you now do.
var givenEmail = "email2#gmail.com";
var dataRef = firebase.database().ref('users');
var query = dataRef.orderByChild('email').equalTo(givenEmail);
dataRef.once('value', (snapshot) => {
snapshot.forEach((userSnapshot) => {
console.log(userSnapshot.val().id);
});
});
Well, I think you are almost there.
users[i].email
you can retrieve the email using this method, and similarly you can do it with id too
users[i].id
Please note that you wanted to find email2#gmail.com but your firebase only have email2
Maybe you would want to change that

Iterate through Firebase ref to load its children

I want to individually load each child of an object from firebase.
A nonworking snippet of code to better explain the idea is given below:
var userId = firebase.auth().currentUser.uid;
firebase.database().ref('/users/'+userId+"/foo/list").once('value').then(function(list) {
var reffoo = firebase.database().ref().child("/foo/");
for (var i = 0; i < list.length; i++) {
ref = reffoo.child(list[i]);
$scope.foo[ref] = $firebaseObject(ref);
}
});
As per my analysis the issue is, $firebaseObject makes async call to firebase but don't know how to make it work?
One option is to obtain a ref to your collection and iterate over using
data snapshot api i.e.,
var ref = firebase.database().ref('/users/'+userId+"/foo/list");
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
$scope.foo[childKey] = childData;
});
});
If you want to maintain actual angularFire reference to an object then $firebaseArray comes to help:
var list = $firebaseArray(ref);
// add an item
list.$add({ foo: "bar" }).then(...);
// remove an item
list.$remove(2).then(...);
// make the list available in the DOM
$scope.list = list;

How to traverse through the auto key generated by firebase push() in React Native?

I have created a search that queries the discogs api for Albums. when I swipe the Album it gets pushed into the realtime database. Firebase auto generates keys for each item pushed which is great, but I am not sure how to handle these keys. How do I get the image url into my require statement? I
here's the function that pushes to the database.
saveToCollection() {
const myFirebaseRef = firebase.database().ref();
myFirebaseRef.push({
albums: `${this.props.album.cover}`
});
}
Any help would be greatly appreciated!
Update with code from comments:
componentWillMount() {
const rootRef = firebase.database().ref();
const albumRef = rootRef.child('albums');
albumRef.once('value', (snapshot) => {
snapshot.forEach((childSnapshot) => {
var childKey = childSnapshot.key;
var childData = childSnapshot.val(); // ... this.setState({albums: childKey.childData}) }); }); }// This is just a sample script. Paste your real code (javascript or HTML) here.
if ('this_is' == /an_example/) {
of_beautifier();
} else {
var a = b ? (c % d) : e[f];
}
You could iterate over the firebase auto generated keys using for...in and push each value in into an array then use the Mustache {{#.}} ... {{/.}} tag pair to iterate over each object in the array.
let arr = [];
for(let autoKey in childData){
arr.push(childData[autoKey]);
}
let tpl = '{{#.}} {{albums}} {{/.}}';
Mustache.render(tpl, arr);

Google Firebase OrderByChild is not working with nested dynamic keys

Order by child (name) is not working when dynamic keys comes between actual reference and data.
Here is my code:
firebase.database().ref('/usersProfile').orderByChild('name').on('value', function(snapshot) {
callback(snapshot);
});
callback(snapshot) {
//console.log(snapshot);
let data = snapshot.val();
self.users = [];
for(let key in data) {
let value = data[key];
value.categId = key;
self.users.push(value);
}
}
And here is my data collected over server:
I think your forward slash might be the problem. It should probably look something like this:
firebase.database().ref().child("usersProfile").orderByChild("name").on("value", function(snapshot) {
callback(snapshot);
});

Retrieving name of object in firebase

I have a list / an array of objects organized numerically which i consider the object name as an 'id'. I am using firebase and I can't figure out how to grab the id number itself. Any help would be great
//js
myFirebaseRef.once("value", function(snapshot) {
var list = snapshot.val();
$scope.items = list
console.log($scope.items)
})
//log $scope.items
[1: Object, 2: Object, 3: Object, 4: Object, 5: Object, 6: Object, 7: Object //...
with angular.forEach like that you can do something near :
angular.forEach($scope.items,function(key,value){
//the key will contain your id
console.log(key);
})
Is this what you're looking for?
myFirebaseRef.once("value", function(snapshot) {
//var list = snapshot.val();
snapshot.forEach(function(itemSnapshot) {
console.log(itemSnapshot.key); // if you're using 2.x that is key()
});
})
Like this. You use obj[key] = value; to set the id with a variable.
function update(node,key,value){
var ref = firebase.database().ref('/');
var obj = {};
obj[key] = value;
ref.child(node).update(obj)
.then(function() {
console.log('Update Ran Successfully');
});
}
This is a real live example, using react and axios to retrieving the name of the object in firebase :
componentDidMount() {
axios.get('/uri.json')
.then(res => {
let fetchedData = [];
for (let key in res.data) {
fetchedData.push({
...res.data[key],
id: key //The key here holds the object's name !
});
}
});
}

Categories

Resources