Google Firebase OrderByChild is not working with nested dynamic keys - javascript

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

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

push to Array in async function is not filtered

var listUsers= [];
for(let item of list){
var profile = await getOne(item.updatedBy);
var gettedUsers = await User.find(queryData).populate({path: "profiles"});
var users = gettedUsers.filter(user => user._id !== profile._id);
if(users) {
for(let gettedUser of users) {
if(!listUsers.includes(gettedUser.profile._id)){
listUsers.push(gettedUser.profile._id);
// do some stuff for the getted user
}
}
}
}
console.log(listUsers); // i get duplicated users
I had added this array list 'listUsers' to filter users and then for each one of them i can do some stuff, but the problem is that i get duplicated users.
Someone could help me ?
The solution is that I changed :
listUsers.includes(gettedUser.profile._id)
to :
var contains = (list, element) => list.some(elem =>{
return JSON.stringify(element) === JSON.stringify(elem);
});
I really don't know waht's the problem but i think I was comparing objects instead of strings. Anyway this solved it ;)

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

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

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

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