I am using Firebase realtime database in Android app, and have data like this:
How can I access that data from javascript.
I just wanna code function to get value of every endTime and compare with current time and if endTime <= Current Time then delete values yellow marked on anther image.
Events is fixed value.
Indjija, Vojvodina and -KsB2mVkpgQe_fRyFFH4 are auto generated so it's possible to have more values like that two.
I know how to solve that in android studio with Java code but I'm interesting about implementing server functions.
The answer to this question is buried deep within Firebase Database Reference.
forEach() is used to get to the child without knowing the child's exact path.
var leadsRef = database.ref('leads');
leadsRef.on('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
});
});
Now childSnapshot will contain the required data, the same thing can also be accessed using child_added.
leadsRef.on('child_added', function(snapshot) {
//Do something with the data
});
The only difference is that in case of forEach(), it will loop through from the start so if any new data will be added, it will also load the previous data but in case of child_added, the listener is only on new child and not the previous existing childs.
Useful Link:
Firebase Read and Write Web
Hope it helps.
Related
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', ...)
First time poster here!
While I was trying to build a little exercise organizer application with ReactJS and Firebase realtime database I encountered a problem with the Firebase push() method.
I have a couple elements on my page that push data to the database once they are clicked, which looks like this:
const planRef = firebase.database().ref("plan");
const currentExName = e.currentTarget.firstChild.textContent;
const exercise = {
name: currentExName,
type: e.currentTarget.children[1].textContent,
user: this.state.user.displayName
};
planRef.push(exercise);
Also, if the element is clicked again, then it gets removed from the database like this:
planRef.orderByKey().on("value", snapshot => {
let exercises = snapshot.val();
for (let ex in exercises) {
if (exercises[ex].name === currentExName) {
planRef.child(ex).set(null);
}
}
});
This is working fine as long as I don't try to push something to the database when I just deleted the last bit of data from it. In that case it gets removed right away.
Data getting removed
Summary:
Write data to the realtime database using ref.push()
Delete data using ref.child(child).set(null) (I tried remove() before, same problem)
Try to push the same data to the database again which leads to the data getting deleted right after being written to the database
I couldn't find anything about this kind of problem so far so I guess I might have made a mistake somewhere. Let me know if the information provided is not sufficient.
Thanks in advance.
Removing a child is an asynchronous operation. I guess what is happening here is the removing operation takes more time than the new writing operation. You will need to await for it if you want to write again on the same key.
planRef.child(ex).set(null).then(() => {
planRef.child(ex).push(new);
});
Or using async/await:
await planRef.child(ex).set(null);
planRef.child(ex).push(new);
Let me know if it worked.
This is my first app project using Google Cloud Functions & Firebase. I'm trying to find away to get a single value of the array that I'm returning and compare it to a set variable and if it matches, update another child's value in that same account.
My App users can add records to the database under their login/user_id that is stored in the database. I'm trying to get a list of the "RecordName" that is a child under that login/user_id that every user has stored in their account.
So basically every "RecordName" in the entire database. When I want to run specials for those records, I need to match the name of that record to the name of the record I have on special and if there is a match, update another child value under that user's account ("special" = true.). This way, when they load their app next time, I have it highlighting that record so they know it's on special.
When I use..
const ref = admin.database().ref(`/store`);
...with the following code...
ref.on('value', function(snapshot) {
// puts ALL items of the object into array using function ..
console.log(snapshotToArray(snapshot));
});
... and the function...
function snapshotToArray(snapshot) {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
});
return returnArr;
};
... I get the entire array just as it is in the database:
-store
-{ones_users_id}
-recordname: value1
-special: false
-{anothers_users_id}
-recordname: value2
-special: false
ect. ect.
If my record on special is called, "Newbie Record", what would be the best way to take out every individual value for the key: "recordname" from the array, compare each one to var = "Newbie Record" and if they match, update the value of the key: "special" to be true?
I'm new to JSON and NodeJS, I've been searching on here for answers and can't find exactly what I'm looking for. Your feedback would be very helpful.
It sounds like you're looking to query your database for nodes that have "recordname": "Newbie Record" and update them.
An easy way to do this:
const ref = admin.database().ref(`/store`);
const query = ref.orderByChild("recordname").equalTo("Newbie Record");
query.once('value', function(snapshot) {
snapshot.forEach(function(child) {
child.ref.update({ special: true })
});
});
Main differences with your code:
We now use a query to read just the nodes that we want to modify.
We now use once() to read the data only once.
We loop over the children of the snapshot, since a query may result in multiple nodes.
We use the reference of each child and then update its special property.
I recommend reading a bit more about Firebase queries in the documentation.
I am trying to imitate an insertion trigger on Firebase using the onWrite method. The insertion is done via POST requests since I am testing it (easiest way I found to check database triggers). The trigger includes writing the Firebase generated ID inside the inserted data as a new property.
My cloud function is this:
exports.onNewSeries = functions.database.ref('/series').onWrite(event => {
"use strict";
console.log(event.data.key);
console.log(event.data.current.key);
console.log(event.data.current);
});
Both first logs contain the same key (series), which actually is the key of the parent node where the new data is appended, instead of the new data key (in the quirky form of -adfaa123sdfasdf). The last log prints a Firebase structure containing the new data as well as the generated key in a _data property, however it is not accessible.
While this can be done manually after a request, I have not seen it automated in a database trigger way.
To get the generated key, make the function trigger on a specific child:
exports.onNewSeries = functions.database.ref('/series/{id}').onWrite(event => {
console.log(event.params.id);
});
Also see the Firebase documentation on handling database events.
I have a realtime database in a Firebase project, with a registered value.
In a minigame, the device reads a QR-Code and store the information. So I want to send the value to Firebase, to the server test if value is the same of the database, and return just "true" or "false".
I can do this, but I get the value to the device and I perform the test in the client. My goal is just send the value and the server will perform the test.
I'm a newbie in Firebase, and I'm not sure if I can do this.
Assuming you have already linked Firebase to your app, you first need to make two references to your database:
var database = firebase.database(); //This links to your database
and
var nodeRef = firebase.database().ref("value/").child("IF APPLICABLE"); //This references to the node you want to compare.
Notice .child(). If the node you want is nested inside another node, you have to use .child("NODE HERE") to reference it.
Next to read the value, you would use:
nodeRef.on('value', function(snapshot) {
nodeValue = snapshot.val();
if (nodeValue == comparisonValue) {
//Do something
});
This calls on your reference and gets its value in your database. Then, within the if statement, you can execute the code that you want. You just have to make sure that they use the same word before the ".on".
Please ask if you need any more clarification!