How to access firebase db sub object elements? - javascript

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.

Related

Shopify Access a product with its id on thank you page without using '/admin' in url

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 :)

How to get firebase id

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"}
})
})

How to assign a variable using firebase javascript

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!

Accessing Firebase push() child

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'));
});

How do I use a variable as a field name in a Mongo query in Meteor?

How would I go about using a variable as a field name in a Mongo query in a Meteor application.
Here is an example...
This runs a find on my request controllers collection after capitalizing the collection name for the parent id of a child. The child is the users field.
window[Meteor.request.controller.capitalise()]["find"]({ _id: Session.get('parent_id'), users: params.child }).count()
As you can see my controller is a variable name for the collection item which allows me to have a single line of code for finding children of controller/collections but I need to be able to set the child field name to a variable. In the above example that would be users but I want it to be a variable name.
I have tried this but it does not work.
window[Meteor.request.controller.capitalise()]["find"]({ _id: Session.get('parent_id'), [Session.get('child_collection_name').decapitalise()]: params.child }).count()
where
Session.get('child_collection_name').decapitalise()
returns users
Any ideas? If I can figure out how to use a variable name in a mongo query in meteor it would reduce my code footprint significantly.
The query is just a JavaScript object, so you can build it step by step:
var query = { _id: Session.get('parent_id') };
var myCustomField = Session.get('child_collection_name').decapitalise();
var myCustomValue = params.child;
query[myCustomField] = myCustomValue;
var count = SomeCollection.find(query).count();
Does that do the trick?

Categories

Resources