How do I delete data stored under a specific key in Firebase using Javascript? The key is generated by Firebase itself and I'm not sure how to reference to the specific key that I would like to delete.
The database is as below:
I would like to delete a specific child's data, in this case I would like to delete the child stored in the key: -LO1M0u_xW4MrolCTwrg
Here is my code:
function deleteComplaintPothole(){
var deleteComplaint= firebase.database().ref("complaintsPothole/complaintId");
deleteComplaint.remove();
document.getElementById("complaints").innerHTML='';
readComplaints();
}
Here is a screenshot of the website showing the complaints with its delete button:
Thanks #Marco Dal Zovo
Finally found the solution. Here is my code:
**
function deleteComplaintPothole(){
$(document).on('click', '.card-body', function(complaintsId){
var complaintsId = $(this).attr('data-complaint-id');
console.log(complaintsId);
var query = firebase.database().ref("complaintsPothole").orderByChild("complaintId").equalTo(complaintsId);
query.on('child_added', (snapshot) => {
snapshot.ref.remove();
window.location.reload();
});
});
}
**
As mentioned in the official Firebase Database Web guide:
Then, you could use orderByChild and equalTo like this:
firebase.database().ref('complaintsPothole').orderByChild('complaintId').equalTo('-LO1M0u_xW4MrolCTwrg').remove();
You can find more informations here: https://firebase.google.com/docs/database/web/lists-of-data
Related
I have a problem retrieveing data from firebase database. The data structure is like this:
posts:{
(Random key):{
post:{
text: "random text"
title: "title of some kind"
username: "username"
}
}
}
and the code I tried to retrieve text is:
database.ref("posts").orderByChild("post").on('value', function(snapshot){
console.log(snapshot.val().text);
})
I am new to this firebase thing, so i am sorry if it's a stupid question.
You have to change your code like this:
database.ref("posts").child(randomKey).on('value', function(snapshot){
console.log(snapshot.child("post").child("text").val());
})
Your snapshot is a DataSnapshot and it contains a child() method that is a DataSnapshot itself. To get your text field you just have to use chield("text") and get then the val().
First you can sort the result by using orderBy on any attributes on post.
For example
var sortedpost = firebase.database().ref('posts').orderByChild('post/text');
Or simply you can also use orderByKey to sort based on the document ID.
After this you can get the result you are looking for using on listener as below.
sortedpost.on('value', function(snapshot){
console.log(snapshot.val());
})
I am trying to get a list of race times for females in a Firebase database that I have. I may have structured the database incorrectly but I can't see why what I am doing isn't working.
I am trying to get a list of users that are female then check what the fastest time is that matches any of the female uid's. But I am stuck with joining the tables.
My database and code looks like this:
var userref = rootref.child("Users");
var raceref = rootref.child('Races');
userref.orderByChild("Gender").equalTo('Female').on("child_added", function(snapshot) {
console.log(snapshot.key);
raceref.orderByChild("uid").equalTo(snapshot.key).once("child_added", function(raceshot) {
console.log(raceshot.key);
});
});
Then the console only shows the snapshot.key not the raceshot.key:
-864646859
-305907999
If I manually put the numbers from snapshot.key in then raceshot.key does show in the console. I don't get any errors so I am confused as to why I can't use the snapshot.key for the equalTo?
The key of a snapshot is by definition a string, so your in your /Users/$id the $id values are strings. But in the /Races/$raceid/uid property you store the value as a number.
My sense is that the comparison fails on the type. If that is indeed the cause, you should be able to fix it by converting the key to a number:
userref.orderByChild("Gender").equalTo('Female').on("child_added", function(snapshot) {
console.log(snapshot.key);
raceref.orderByChild("uid").equalTo(parseInt(snapshot.key)).once("child_added", function(raceshot) {
console.log(raceshot.key);
});
});
I want to delete all rows with a specific name. In this example "gerda65".
I can delete one row by doing
mDatabase.child("shares")
.child("senneken-shares")
.child("1515596541713UjBPLm7rHMXGy6leFhj5H9VTQwh1")
.child("gerda65")
.removeValue();
But I want to delete all the gerda65 values under my "senneken-shares".
Here is my firebase db structure:
Does anyone how to do that?
Thank you in advance.
You can use Queries for that, since they allow proper data filtering. You would do something like:
var ref = mDatabase.child("shares")
.child("senneken-shares");
var query = ref.orderByChild("gerda65").equalTo(true);
This will return a list of all the "gerda65". So you need to add a listener to read this data, iterate through it, getting their keys and deleting them:
query.once('value', function(snapshot){
snapshot.forEach(function(snap){
ref.child(snap.key).remove();
});
});
My firebase db structure is given below,
users
fb-user-key1
user1-details1
Tags
Tag-key1
"name":"value"
Tag-key2
"name":"value"
fb-user-key2
user1-details2
Tags
Tag-key1
"name":"value"
Tag-Key1 & user-key's are generated by firebase with push(). firebase code to access the content is,
var fbref = firebase.database().ref("users");
fbref.child("Tags").on("child_added", function(e){
var Tagobj = e.val().name;
console.log(Tagobj);
});
This one is not returning anything. I am not able to access name:value pair in the above data structure.
`
adding modified code,
firebase.database().ref("users").on("child_added",function(eāā) { var Tagobj = e.val().Tags; });
Output of the above code is output data structure
How to access that name value pairs?? firebase keys are issue?
Not getting, where I am wrong. Appreciate your inputs.
Since Tags is a child property of each user, then you have to read it off of each user object.
If you want all Tags for all users, assuming Tags for each user is not updated after a user is created, you can do this:
tagsPerUserId = {};
firebase.datatabs().ref('users').on('child_added', function(snap) {
tagsPerUserId[snap.key] = snap.value().Tags;
// TODO: Notify view that tagerPerUserId is updated and needs to be re-rendered
console.log(`Tags for userId ${snap.key}: ${snap.value().Tags}`);
});
This way you will also get Tags of new users when they are created, but you will not get updates to Tags of existing users.
Anyone know how to get the Firebase unique id? I've tried name(), name, key, key(). Nothing works.
I am able to see the data but I have no idea how to get the id back. I need it.
//Create new customers into firebase
function saveCustomer(email) {
firebase.database().ref('/customers').push({
email: email
});
firebase.database().ref('/customers').on("value", function(snapshot) {
console.log(snapshot.val());
console.log(snapshot.value.name());
}, function(errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
The call to push will return a Firebase reference. If you are using the Firebase 3 API, you can obtain the unique key of the pushed data from the reference's key property:
var pushedRef = firebase.database().ref('/customers').push({ email: email });
console.log(pushedRef.key);
The key for the pushed data is generated on the client - using a timestamp and random data - and is available immediately.
Calling push() will return a reference to the new data path, which you can use to get the value of its ID or set data to it.
The following code will result in the same data as the above example, but now we'll have access to the unique push ID that was generated:
// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push();
// Get the unique ID generated by push()
var postID = newPostRef.key();
Documentation.
but this method won't work when you also need the id beforehand
for example to save it in the database itself.
Firebase suggests this:
// Add a new document with a generated id.
var newCityRef = db.collection("cities").doc();
--for some reason, push() and key() didn't work for me. also in this case the reference contains the whole path. so need a different method for getting the id.
Doing this below helped to get the id from the reference and use it.
const ref = db.collection('projects').doc()
console.log(ref.id) // prints the unique id
ref.set({id: ref.id}) // sets the contents of the doc using the id
.then(() => { // fetch the doc again and show its data
ref.get().then(doc => {
console.log(doc.data()) // prints {id: "the unique id"}
})
})