I have some data in a directory and I want to retrieve the value of a certain object e.g. Get the value of "NVR".
Another task I need to do is have a 'for' loop to go over and get information about different questions from the following data. I would need to get the number e.g. "001" and the items inside of that subdirectory. And it would also need to go through every directory in 'questions' such as NVR or MTH.
For the first one, you can try this:
firebase.database().ref().child("unique").on('value', function(snapshot) {
var datas = snapshot.val();
var nvr=datas.NVR;
)};
For the second one try this:
firebase.database().ref().child("questions").child("NVR").on('value', function(snapshot) {
snapshot.forEach(function(child) {
var keys=child.key;
var datas = child.val();
var correcta=child.val().correctAnswer;
var num=child.val().numberOfAnswers;
//etc
});
});
the first one the snapshot will be at unique, then you will be able to retrieve the child NVR.
In the second one, you iterate inside NVR and retrieve the key using var keys=child.key;
Try something like this for going through every directory in questions and for each one getting all the questions in it :
firebase.database.ref('questions').on('value').then((snapshots) => {
//print whole questions group (nvr, mth, etc)
console.log(snapshots.val())
snapshots.forEach((snapshot) => {
//print each question in question group
console.log(snapshot.val())
})
}
Both Peter's and Egor's answers load all data under unique. Since you know the key of the item whose value you want to retrieve, you can load this more efficiently with:
firebase.database().ref("unique/NVR").on('value', function(snapshot) {
var nvr=snapshot.val();
)};
Related
I am currently trying to append data through I pull from Firebase to a table in the order of newest to oldest posts. I currently have the following setup in my code base (simplified to address issue):
var theDataRef = new Firebase('https://my-app.firebaseio.com');
theDataRef.orderByChild("timestamp").limitToLast(25).on('child_added', function (snapshot) {
var message = snapshot.val();
displaytableRow(message.name, message.text);
}
function displaytableRow(name, message) {
$("#sch").find('tbody > tr:first')
.before($("<tr><td><div>" + name + ":" + message + "</div></td></tr>"))
};
I have tried to create a table that displays newest to oldest data by using both firebase and jquery techniques but every time my data is displayed in a random order. I have a working timestamp field on every record in my data as well but even ordering by that does not solve the problem. Has anybody had any experience building this successfully?
EDIT:
The timestamp is gotten with the following code:
var timestamp = Firebase.ServerValue.TIMESTAMP;
And the database architecture is structured like so:
If you want to order your posts from newest to oldest you can do the following:
1/ Store a field in your post that is the inverse of the TimeStamp as follows:
var tDate = new Date().getTime();
var postData = {
//.....
timestampInverted: (0 - tDate),
//.....
};
2/ Query your posts ordered by this field as follows:
theDataRef.orderByChild("timestampInverted").limitToLast(25).once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
displaytableRow(childSnapshot.val().name, childSnapshot.val().text);
});
});
It is important to note that theDataRef.orderByChild("timestampInverted").limitToLast(25) returns a Query, which returns a DataSnapshot : Therefore you need to use snapshot.forEach() (see doc here) to iterate over the different posts items.
Also note that "even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you always need to loop over the snapshot".
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();
});
});
I am trying to access a specific product using its id from the below url,
https://tempstore.myshopify.com/products/1234.json
Its giving me 404 error.
Although, I am able to access all products as below:
https://tempstore.myshopify.com/products.json
I have to access the product which was just processed in checkout process.
I have its id as below:
var products = Shopify.checkout.line_items;
products will contain an array of product id's only which are processed in checkout.Now I need to access all other properties of these products.
I can surely do this:
https://tempstore.myshopify.com/admin/products/1234.json
But it requires Authentication.
Any thoughts?
From the frontend, you need to have the product handle to get the JSON object:
https://tempstore.myshopify.com/products/[handle].js
or
https://tempstore.myshopify.com/products/[handle].json
(Note that the returned values from the .js and .json endpoints are quite different from each other!)
Like you point out, the Shopify.checkout.line_items array of objects only has the product IDs, not the product handles. We're not completely out-of-luck, though, because we can get the entire list of products in the store including the product handles by hitting the /products.json endpoint.
Of course, this means grabbing a potentially huge JSON object just to get information that we should've had included in the checkout line items... but unless there's some alternate source of the line item information available on the checkout page, looping through the entire list may be what you need to do.
So your end code would look something like this:
Checkout.jQuery.getJSON( // Or whatever your preferred way of getting info is
'https://tempstore.myshopify.com/products.json',
function(prodlist){
for(var p = 0; p < prodlist.length; p++){
var prod = prodlist[p];
// Find if Shopify.checkout.line_items contains prod.id, left as exercise for the reader
if(found){
Checkout.jQuery.getJSON(
'https://tempstore.myshopify.com/products/' + prod.handle + '.js',
function(product){
/* Whatever needs to be done */
})
}
}
}
)
Hope this helps!
var shop = Shopify.shop;
var lineItems = Shopify.checkout.line_items;
var url = 'https://' + shop + '/products.json?callback=?';
var requiredData = [];
$.getJSON(url).done(function(data){
lineItems.forEach(function(lineItemProduct){
data.products.find(function(product){
if(lineItemProduct.product_id == product.id){
requiredData.push(product);
}
});
});
});
console.log(requiredData);
This is how I solved it, If it helps anybody :)
Reading the firebase doc this line:
database.ref('/').once('value').then(function(snapshot)
That is from a paragraph titled "Read data once" which I'm assuming reads in all the data from the database.
I'm just struggling to figure out how to assign data from the object that is returned to a variable in javascript.
What I want to do is populate a dropdown list with place names.
For instance if I have a field called Location in the db containing place names eg Sydney, Melbourne, Brisbane how would I get the data from the returned object and assign it a variable called place so I can then use the place variable to populate the html dropdown list.
You can try with this simple code -
database.ref('/').once('value').then(function(snapshot){
var list = snapshot.val();
if(list)
{
for (item in list)
{
itemIndex = item;
item = list[item];
//access your properties of the object say - item.location
}
}
});
You have to user 'child_added'
example:
var dbRef = firebase.database().ref().child('someChild');
dbRef.on('child_added', function(snap){
var res = snap.val().theValueYouNeed;
});
The code above gets the specific child in your db like this:
someChild:{
theValueYouNeed:"some value"
}
Then you can populate your list with the values.
I hope this helps!
I'm slowly getting into Firebase but have what is probably a stupid question. If I am adding children to a reference using push(), how do I retrieve/delete them if I don't save the generated push ID?
For example, take this root:
var ref = https://myaccount.firebaseio.com/player
And if I write a new entry to /player:
var new_player= ref.push({
name:"User",
country:"United States"
})
Firebase generates a push ID for that:
https://myaccount.firebaseio.com/player/-JxgQCQsSLU0dQuwX0j-
which contains the information I pushed. Now lets say I want to retrieve or remove that player? Should I store the generated ID as a child of itself using .key() and .set()?:
//this will get -JxgQCQsSLU0dQuwX0j-
var _newPlayerKey = new_player.key();
//updates the record I just created
var update_player = ref.set({
name:"User",
country:"United States",
ref: _newPlayerKey
})
I don't see how else to access that object by it's generated ID... is there a better way to set this up?
Why are you doing that can't use the key() method, it should be adequate in almost all cases i.e.
playersRef.limit(10).on('child_added', function (snapshot) {
var player = "<p>"+ snapshot.val().name +" <button data-value='"+snapshot.key()+"'>Delete</button></p>";
$(player).appendTo($('#messagesDiv'));
});