Firebase retrieve data under certain child - javascript

I was having some trouble when trying to retrieve from firebase. Here is my firebase structure:
What I tried to do is firstly, I wanted to get list of receiptItemID in the first picture. Then, after I get the IDs, for each ID, I wanted to get its quantity and type. After that, I will store them into array and perform some sorting.
Here is my code:
var query = firebase.database().ref('');
query.once( 'value', data => {
data.forEach(subtypeSnapshot => {
var itemKey = subtypeSnapshot.key;
var query = firebase.database().ref('').child(itemKey);
});
});
});
I managed to get the itemKey. However, when I tried to get the details of each receiptItem by the console.log that part, it prints out undefined for both. Any ideas on how to retrieve the data?

You don't need the forEach cycle, it's one level too deep. Instead, use the 'data' argument directly. This new callback should work:
var itemDetail = data.val();
var subtype = itemDetail.type;
var quantity = itemDetail.quantity;
console.log(subtype + ' ' + quantity);
In the first iteration of the forEach of your sample code, itemDetail will be equal to "Farmland" instead of the whole object; thus, subtype and quantity are null. In the new callback, itemDetail will be equal to the whole object, so subtype and quantity can be successfully declared.

var query = firebase.database().ref('receiptItems').child(itemKey);
query.once( 'value', data => {
var itemDetail = data.val();
var subtype = data.type;
// you may try data.toJSON().type as well
var quantity = data.quantity;
// try data.toJSON().quantity
console.log(subtype + ' ' + quantity);
});
In second retrieval you already have access to receiptItems/itemKey .This is a particular entry in receiptItems , not the whole receiptItems array.
So no need to apply data.forEach() once more as there is only one record. We apply data.forEach() to fetch an array of records/object. In your case it is just one entry.

Related

How can a new data be added to firebase without the post keys?

I use the following code to add new data to firebase.
var postData = {
NSN: NSN,
ProductName: ProductName,
AssociatedContractNumber: AssociatedContractNumber,
ItemQuantity: ItemQuantity,
viewable_by: uid,
};
InventoryID = firebase.database().ref().child('Posts').push().key;
var updates = {};
updates['/Businesses/' + uid + '/Inventory/' + InventoryID] = postData;
what i want to do is to create a list of NSNs in child "NSN" without the uniquely generated post ids. But all the attempt to add just the NSN to child NSN keeps replace the old with the new NSN. so instead of something like 10 different NSNs i only got 1 which is the most recent one added.
I used this code initially
var postNSN = {
NSN: NSN,
};
updates['/Businesses/' + uid + '/National_Stock_Numbers/' + NSN] = postNSN;
the above only replaces the existing number with the new one instead of adding the new one
I also tried this
var NSNref = database.ref('/Businesses/' + uid + '/NSNs/')
NSNref.set({
NSN: NSN,
})
but nothing happens. How can I add a new NSN to child NSNs without the uniquely generated keys?
Just use push()
Say if you had and NSN object like
var NSN = { ... }
firebase.database().ref().child('Posts').push(NSN);
Doing this will always push the item to the end of your NSN array and firebase will take care creating unique key at the time of pushing.
Remember firebase don't know about arrays it only knows about objects.

I need to take max value from different id of database from $scope to others

So I have this database:
I need to sort those child id(s) (from type1 to type10), show sorted value at UI and the biggest value of id will be the new variable that I want to put that $id (example in this case the biggest value is 84.5 which has an $id named type2) to be sifat="type2".
Should I declare them in a new variable and then sort it?
You'll have to do sorting on the client, but you can use angularfires $firebaseArray to get everything into an array at least:
$firebaseArray(...child('result')).$loaded().then(function(types){
$scope.types = types;
})
And then sort in the dom (or wherever else you'll need too)
<div ng-repeat="type in types | orderBy:'value'"></div>
https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebasearray
I solved this
fireBaseData.refUser().child($scope.user_info.uid).child("result")
.orderByValue()
.limitToLast(1)
.on("value", function(snapshot){
snapshot.forEach(function(data){
console.log("The "+ data.key()+" score is "+ data.val());
$scope.highestval = data.val();
$scope.highesttype = data.key();
fireBaseData.refUser().child($scope.user_info.uid).update({ // set
sifat: $scope.highesttype
});
});
}
and also the filter function from #Mathew Berg is working as well, thanks

angularjs Firebase Databse filtering using equalTo and passing an array

I am trying to filter my output of DatabaseONE by values of a child of another DatabaseTWO:
var myquery = DatabaseRef.ref("mydatabaseONE").orderByKey().equalTo("-KUTPrs6ARZXjbjtNr7O");
$scope.mylist = $firebaseArray(myquery);
For my second database, I have set up this service to get the keys and values of the child (i.e. books) I am querying in the DatabaseTWO:
app.service('MyUser', ['DatabaseRef', 'firebase', function(DatabaseRef, firebase) {
var userId = firebase.auth().currentUser.uid;
userbooks: function() {
return(
DatabaseRef.ref('/users/' + userId).once('value')
.then(function onSuccess(snapshot) {
return snapshot.val().books;
})
);
}
and the result is like this when I call it like below and console log it :
var mybooks = MyUser.userbooks();
My question is how can I pass the values of my DatabaseTWO promise value object into the first query using DatabaseONE and put it as an array in equalTo ? As you can see, I have manually inserted one example value, and it works, but I want to put all three of them (marked in red) as an array?
Or if you have any other creative ideas to filter using equalTo?

Get the value of differents attributes with localStorage.getItem()?

I am trying to create a little app, and I need to store some data.
I store them like this :
localStorage.setItem(taskID, taskTitle, taskTotal, taskActual, taskProgress);
(the taskID taskTitle, etc.. are values that I get from a form)
So this actually works well, and I have only one problem :
I can easily retrieve the taskID using:
for (i = 0; i < localStorage.length; i++) {
var taskID = "task-" + i;
};
but how can I retrieve the other values? Like if I want to retrieve taskActual value, how can I easily do that?
That's not how it works. Your code sets the value taskTitle under key taskID, the rest of arguments is discarded. Then you can only retrieve the taskTitle using localStorage.getItem( taskID ).
If you want to store more attributes you need to either store multiple items, for example:
var taskID = 'task-1';
localStorage.setItem(taskID +'-title', taskTitle);
localStorage.setItem(taskID +'-total', taskTotal);
// etc
// to retrieve:
var title = localStorage.getItem('task-1-title');
or store a serialized JSON:
var taskId = 'task-1', taskData = { title : 'task title', total : 'task total' /* etc.. */ };
// store
localStorage.setItem(taskID, JSON.stringify( taskData ) );
// retrieve
var task = JSON.parse( localStorage.getItem('task-1') );
// now you can use task.title, task.total etc
in local storage you are saving a key and a value. In this instance your 'keys' are the named items, i.e TaskId, taskTitle, etc. You need to have a corresponding value associated with the key. For example: localStorage.setItem('taskId',1); In this example, should you call localStorage.getItem('taskId'), the result would be 1, as it is it's corresponding value.

How to replace ' / ' with '-' inside ObservableArray ? Knockout js

Well i am trying to pass an observable array via ajax call to my controller but i get every value there except date . i get something like '01-01-01' etc .
I found the issue but unable to fix that as i dont know how to replace / with - .
My ObservableArray have around 10 list items each list item holds a many properties out of those startDate holds the date like ("23/10/2014") . i just need something like ("23-10-2014") .
Tought of posting my function's and more i hope thats not required in this case i believe .
Let me explain with bit of code and sample data :
function myarray()
{
var self=this;
self.startDate=ko.observable("");
self.name=ko.observable("");
self.place=ko.observable("");
}
MyObservableArray :
self.Main= ko.observableArray();
In between i do some stuff to load Data into self.Main and i am sending self.Main to controller having data like below :
self.Main[0] holds :
startDate() -->gives you "23/10/2014" //individual observables inside onservable array
name() --> "jhon"
place()--> "croatia"
Likely
self.Main[9] holds :
startDate() --> "29/05/2012"
name() --> "pop"
place()--> "usa"
I am trying like i want to alter the self.Main() and replace the startDate and use the same self.Main to send to my controller . Once after replacing in self.Main when i check date the / should be replaced with - .
Possible solution : i can use a different observable array and push all the VM's of Main into it but i am trying to do on self.Main without using other .
If someone can show some light it is much appreciated .
What I got that you are facing problem in escaping / in replace.
Try this
"(23/10/2014)".replace(/\//g,"-") //returns "(23-10-2014)"
I tried something for you using simple JS
var arr = [{date:"(23/10/2014)"},{date:"(23/10/2014)"},{date:"(23/10/2014)"},{date:"(23/10/2014)"}];
arr.forEach(function(obj){obj.date = obj.date.replace(/\//g,"-")});
console.log(arr) //will print date field as "(23-10-2014)" for all objects.
One solution would be to add a computed value that returns the array with the right values.
self.Main = ko.observableArray([...values here...]);
self.MainComputed = ko.computed(function() {
var computedArray = [];
self.Main().forEach(function(item) {
var newItem = myarray(); //Create a new item.
newItem.name(item.name());
newItem.place(item.place());
newItem.startDate(item.startDate().replace(/\//g,"-"));
computedArray.push(newItem);
});
return computedArray;
});
Then use the computed value in the places where you need the values with -.
I can think of two other ways to solve your issue, when taken into account that you want to use self.Main:
Replace the / with - before setting startDate on your item.
Change startDate to a computed value while storing the original value in another variable.
The first solution should be pretty straight forward (provided that it is a valid solution).
The second solution would look something like this:
function myarray()
{
var self=this;
self.originalStartDate = ko.observable("");
self.name = ko.observable("");
self.place = ko.observable("");
self.startDate = ko.computed(function() {
if(self.originalStartDate()) {
//We can only replace if the value is set.
return self.originalStartDate().replace(/\//g,"-");
}
else {
//If replace was not possible, we return the value as is.
return self.originalStartDate();
}
});
}
Now when you set the values you do something like:
var item = myarray();
item.originalStartDate = "01/01/2014";
Then when you get the value of startDate you would get "01-01-2014".
I haven't used Knockout.js but you can do this with a Javascript replace:
var str = [your array value] ;
var res = str.replace("/", "-");
For more information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Categories

Resources