Firebase remove() entire nested array in database - javascript

How does one delete an entire nested child from a Firebase database by referencing an entry to find the desired point of deletion?
For example, I have two entries nested under (list). (1) -KcxacywN4EkvwAzugfV and (2) -KcxaeBAIW-WgLAsajvV. I want to remove (2) -KcxaeBAIW-WgLAsajvV from the database using it's ID -KcxaeBAIW-WgLAsajvU-4-725391765511696 (See picture below).
I have a button setup for each database entry, to display a remove button. Each button, contains the data- or ID for each database entry.
rootRef.on("child_added", snap => {
var title = snap.child("title").val();
var link = snap.child("link").val();
var type = snap.child("type").val();
var id = snap.child("id").val();
$("#table_data").append("<div class='col-lg-4'><div class='card card-app'><div class='card-block'><h4 class='card-title'>"+ title +"</h4><small>"+ type +"</small><hr><a href='"+ link +"' target='_blank'>Download</a> <a class='user float-right' onclick='removeClick()' data-name='"+ id +"'>Remove</a> </div></div></div>");
});
The onClick event and associated id for the button, trigger this function. My mental idea, is to then take the ID from data- to delete its nested child, (2) -KcxaeBAIW-WgLAsajvV from the database. Same process for all other nested entries.
function removeClick() {
$(".user").click(function() {
rvm = $(this).attr("data-name");
});
alert(rvm);
firebaseRef.remove(rvm);
}
I've studied https://firebase.google.com/docs/database/web/read-and-write and can't seem to figure out the actual deletion of the nested entry. How can I use remove() or maybe another method to accomplish this?
I have been trying this, to get a better understanding.
firebaseRef.child(rvm).remove();
Since rootRef, is how I'm viewing data. I tried.
rootRef.child().remove();
This simply deletes the whole database...
Final running code:
function removeClick() {
$(".user").click(function() {
rvm = $(this).attr("data-name");
});
alert(rvm);
var query = rootRef.orderByChild("id").equalTo(rvm);
query.once("value", function(snapshot) {
snapshot.forEach(function(itemSnapshot) {
itemSnapshot.ref.remove();
});
});
}

You can only remove an item if you know its key. So given your current structure, you will first need to look up the key for the id you mention.
Assuming you have a variable ref that points to the root of the database:
var listRef = ref.child("list");
var query = listRef.orderByChild("id").equalTo("-KcxaeBAIW-WgLAsajvU-4-725391765511696");
query.once("value", function(snapshot) {
snapshot.forEach(function(itemSnapshot) {
itemSnapshot.ref.remove();
});
});
If you have only a single child with the id, you should consider restructuring your database to use the id as the key. If you do that, you could remove the item with:
listRef.child("-KcxaeBAIW-WgLAsajvU-4-725391765511696").remove()

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.

Firebase retrieve data under certain child

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.

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?

How to fetch existing JSON that exists in data-attr and update that

In the given fiddle , click on Addons buttons and on selection and unselection
of Checkboxes , i am trying to update the data-attr
array present as data-stuff .
Once i set the data how can i fetch the existing and update it with new data .
http://jsfiddle.net/kgm9o693/9/
// checkbox checked
$(document).on('click', '.ui-checkbox-off', function (event) {
var vendoritemsdata = $(".lastItm_Wrap").data('stuff');
var checkboxid = $(this).next().attr("id");
var cost = $(this).attr("cost");
var toppcrusts = [];
toppcrusts.push({
'name': checkboxid,
'cost': cost
});
if (vendoritemsdata.length == 0) {
$('.lastItm_Wrap').attr('data-stuff', toppcrusts);
}
else {
var existingdata = $('.lastItm_Wrap').data('data-stuff');
}
});
Could you please tell me how to resolve this ??
You are trying to use the DOM as a variable. It should be the other way around. Use the DOM only to show results (total cost in your case). But before that keep everything into an array serialize the array if you need it as json or data-stuff.
Examine the example at the bottom of this http://api.jquery.com/serializeArray/
If you want to keep doing it your way, convert the data to JSON and use this:
Set data
$('.lastItm_Wrap').attr('data-stuff', JSON.stringify(toppcrusts) );
Get data
var existingdata = JSON.parse( $('.lastItm_Wrap').attr('data-stuff') );
http://jsfiddle.net/kgm9o693/12/

Categories

Resources