I am using firebase and want to loop through my messages that I have and delete certain ones based upon a user's uid.
Here is an image of what I have for the structure of my data:
So far I know you would start of as something like:
Firebase.database().ref('messages').on('value', snapshot => {
snapshot.forEach(snap => {
if(snap.val().user.id === currentUser.uid){
//delete message here
};
});
});
Where do I go from here?
First of all, you probably want to use once() instead of on(). If you modify the contents of the database that you're working with, your on() will get triggered again for each change. You can see how that might be problematic for your case, if you only want to loop through the data once. Definitely learn about the difference between once() and on().
If you have a DataSnapshot type object, you can delete the contents of the database at its location with
snap.ref.remove()
Definitely read up on the Reference object type.
Related
I am trying to access the child value of a unique key value (that had been "pushed") within Firebase. Currently, my database looks like this: I want to access the value of "emailOfUser"
I am very new to Firebase so I am not familiar with the functions. Currently, this is my method of obtaining other values for a different section of the database:
Thank you so much for any feedback!
I've tried different methods to accessing this data within the Firebase, but I cannot get it to work/the methods I were using were outdated. I also tried to "update" the Firebase instead of "pushing" the values to prevent a unique key from generating, but it simply overwrote my current data rather than appending something new.
If you want to load all the users who voted and print their emails, you can do that with:
get(child(dbref, 'usersWhoVoted')).then((snapshot) => {
snapshot.forEach((childSnapshot) => {
console.log(childSnapshot.key, childSnapshot.val().emailOfUser);
});
})
Note that your current structure allows a user to vote multiple times. If you want to only allow them to vote once, use some identifier of the user as the key in your database structure:
userVotes: {
"uniqueIdOfUser1": "valueTheyVotedOn",
"uniqueIdOfUser1": "valueTheyVotedOn",
...
}
Now each user can by definition only vote once, If they vote again (assuming your security rules allow that), their new vote will simply replace the existing vote.
I have a database collection with readings, each new reading needs to be checked if it's out of the ordinary, if it is, there needs to be an alert sent.
So i'm using db.ref('collection').on('child_added', (child => { check(child); });
The problem with the .on function is that when the listener is added, all previous data is also read.
So how do i read a collection that only reads the changes in the database, also when the listener is first added? Or if that doesn't work, how do I differentiate the already added data with the new data?
The Firebase database synchronizes the state of whatever query or reference you attach your listener to. There is no option to only get new nodes built into the API.
If you want only new nodes, you will have to:
Ensure each node has an associated timestamp or order. If you're using Firebase's built-in push() keys, those might already serve that function.
Know what "new" means to the client, for example by either keeping the last timestamp or push key that it saw.
And then use a query to only request nodes after the stores timestamp/key.
So for example, if you only want to read nodes that are created after the moment you attach the listener, you could do something like this:
let now = db.ref('collection').push().key; // determine current key
db.ref('collection').orderByKey().startAt(now).on('child_added', ...)
I want to read last message node as shown in image below.
I am using below query to retrieve last message where suid and ids are known(as shown in img). but not working.
firebase.database().ref("Messages/"+suid).child(ids+"/chat").orderByKey().limitToLast(1);
How to retrieve last message from firebase realtime db and display it to my console? Thanks
Your existing code looks fine, so let's store that query in a variable first:
const query = firebase.database().ref("Messages/"+suid).child(ids+"/chat").orderByKey().limitToLast(1);
Now you can read the message(s) this query matches with either once() or get(). I'll use once(), since it's much older and hence you're more likely to find examples of it elsewhere:
query.once("value").then((snapshot) => {
snapshot.forEach((message) => {
console.log(message.val().message.msg);
});
})
Some things to note here:
Since a query may have multiple results, the snapshot contains a list of those results. Even if there's only a single result (like here), the snapshot is a list of one result. To loop over these results, we use snapshot.forEach().
Your msg is nested under message in each child, so we use message.val().message.msg to get at its value.
Reading firebase real time database docs it is not clear when the child_added event triggers exactly. It says it triggers when a new child is added to a node, so far so good. The docs also say that, if you want to get the next available unique Id on a path, you just call push() on that path to get a reference that will have a unique ID. However, it is not clear if this empty push call will be considered an event of child_added or if it will be ignored. Once you get the ID, you can not push again or you will get another ID (that is just my guess) so you just set the given reference with the data you want it to contain. It is not clear either if this last operation will trigger a child_added event.
Let me ilustrate with a bit of code with inline questions:
const dbRef = db.child('todos')
const newTodoRef = dbRef.push() // does this trigger child_added event?
newTodoRef.set({ id: newTodoRef.key, name: 'test' }) // and does this?
Calling push() without any arguments does not write any data, so it does not trigger any events yet. It merely creates a reference in the code to a new unique location.
Calling set(...) on this reference does then write data, so does trigger events.
Code for deleting something (not working with this.task.id or this.task)
const docRef = firebase.firestore().collection('users').doc(firebase.auth().currentUser.uid)
docRef.collection('tasks').doc(this.task.id).delete()
It looks like you are not handling the promise with a then or async/await, like the docs indicate https://cloud.google.com/firestore/docs/manage-data/delete-data#node.js.
Also, your code implies the tasks are nested within the individual users document. If this is not the case, you might be referencing the wrong collection entirely. I suggest first doing a .get().then(res => console.log(res)) for both the user & their task. If you can't get the document, you can't delete it.