I am struggling how to retrieve data from firebase having a child key, such as uid.
here is the structure of my firebase.
Currently I am making an admin panel which can read the order placed by each user and render it through flatlist in react native, but it seems that I can't access their order because every time the user places an order it is stored on their unique User.id
I don't know how to make a reference to the User.id child like firebase.database().ref(orders/${AllUserId}/products)
You can use forEach loop to fetch ids and can get values as so
firebase.database().ref('order').on('value', (snapshot) => {
snapshot.forEach((child) => {
uid = child.key; // gives uid1
child.forEach((snap) =>{
var id = snap.key; // first iteration gives uid2
firebase.database().ref('order/'+uid+'/'+id).on('value', (snapchild) => {
snapchild.forEach((snapshotchild) =>{
console.log(snapshotchild.val());
});
});
});
});
});
This could be more insightful.
Related
I want to retrieve the data from donation and display it in a table. I was able to retrieve the user data from Users and displayed it on a table. But now I don't know how I will be able to retrieve the data from donation.
This is my database structure in Firebase. Note: All of the data that was entered came from a mobile app created in Android Studio.
This is the code that I made when retrieving the User data.
function AddAllITemsToTable(User) {
id=0;
tbody.innerHTML="";
User.forEach(element => {
AddItemToTable(element.uid, element.fullName, element.organization, element.contactPerson, element.contactNo, element.location, element.emailAddress, element.status);
});
}
function GetAllDataRealtime() {
const dbRef = ref(database, 'Users');
onValue(dbRef,(snapshot) => {
var Users = [];
snapshot.forEach(childSnapshot => {
Users.push(childSnapshot.val());
});
AddAllITemsToTable(Users);
})
}
window.onload = GetAllDataRealtime;
Since you're calling onValue on /Users, you already get all data for all users and all of their donations. To process the donations in your code:
const dbRef = ref(database, 'Users');
onValue(dbRef,(snapshot) => {
var Users = [];
snapshot.forEach(userSnapshot => {
Users.push(userSnapshot.val());
userSnapshot.child("donation").forEach((donationSnapshot) => {
console.log(donationSnapshot.key, donationSnapshot.val());
});
});
AddAllITemsToTable(Users);
})
As I said in my comment, I recommend reading the Firebase documentation on structuring data, as the way you nest donations under each user does not follow the guidance on nesting data and keeping your structure flat.
I have this function:
firestore.collection('customers').doc(userID).collection('subscriptions')
.where('status', 'in', ['trialing', 'active']).get()
.then(activeSubscriptions => {
// if this is true, the user has no active subscription.
if (activeSubscriptions.empty === true) {
console.log("line 31")
{signOut(props.history)}
subStatus = "inactive"
}
});
Basically, in firestore, I have a customers collection, a doc with the user id, and then the subscriptions collection in which is created upon a user processing stripe. In the subscriptions collection, it has a doc which is the subscription id, and I have some fields I want to grab. See the attached picture:
I want to grab the current_period_end data so I can put it out on screen. how would I do this?
If you are looking to access fields from a firestore document, you can do it by specifying the field in square brackets.
With a firestore structure like /customer/cus123/subscriptions/sub123 I was able to obtain a timestamp field of sub123 with this code:
let cusRef = db.collection('customer').doc('cus123').collection('subscriptions').doc('sub123');
cusRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
}
else
{
console.log('Name: ',doc.data()['name']);
console.log('Tmsp: ',doc.data()['tmsp123']);
}
});
I hope you find this useful.
I have few posts in my app, and I want that when user selects one of them, he to be redirected to a Post.html page which contains all details about that specific product. I have two methods, createPost() for creating a product dynamically where I pass postId in order to keep track of that product, and getPosts() to get the posts from database. I am saving all posts in an array in localStorage to have data about the selected product in Post.html. I added an addEventListener() but not sure how to use it. The problem is that I am stuck how to get the information of that post and pass it to Post.html.
function getPosts() {
firebase
.firestore()
.collection("products")
.get().then(snapshot => {
let products = [];
snapshot.docs.forEach((doc) => {
products.push(doc.data());
createPost(
doc.data().title,
doc.data().description,
doc.data().price,
doc.data().postId
);
});
localStorage.setItem(`${products}`, JSON.stringify(products));
})
.catch((err) => {
console.log(err);
});
}
function createPost(title, description, price, postId) {
let div = document.createElement("div");
div.setAttribute("class", "product-home-show");
......
div.appendChild(divSellerRoundImage);
div.appendChild(divSellerName);
div.appendChild(divProductDescription);
div.appendChild(divProductName);
div.appendChild(divProductPrice);
productsCollection.appendChild(div);
div.addEventListener("click", function () {
// console.log(localStorage.getItem());
// window.location.href = "post.html";
});
}
You can get data from localStorage on another page. Use localStorage.getItem(keyName); Also keep in mind the first argument to setItem is the key name. I'd recommend changing your code to: localStorage.setItem("products", JSON.stringify(products));. Then you'll be able to retrieve your product list with they key "products."
Also, if you're saving an object, you'll need to parse it since it will be saved as a string. You can use JSON.parse
For example:
var retrievedData = localStorage.getItem("products");
var productListObject = JSON.parse(retrievedData);
You can save the selected post ID in another value in local storage, or a cookie. Lastly, you may want to consider using sessionStorage if you don't need the data stored after the session is over. See this link for more information
I need to iterate the users of my Firebase Database. I have a token for each user, and I want to send a notification to each user of the database.
My database looks like this:
console.log('Sending a notification to all users');
var ref = functions.database.ref('/users');
for (var token in ref){
console.log('Hello from: '+ ref.token);
}
Your ref is just a reference to a specific path in Firebase Realtime Database. You haven't queried it, so you don't have anything back yet. Try this:
console.log('Sending a notification to all users');
var ref = functions.database.ref('/users');
// Query the database
ref.once('value').then((usersSnapshot) => {
// Get back all the user records and iterate through them.
usersSnapshot.forEach((userRecordSnapshot) => {
// I'm guessing your record id is the token?
const token = userRecordSnapshot.key
// To get the other values, for example
const email = userRecordSnapshot.val().email
});
});```
I am using react with firebase realtime database
So i have this firebase data and i want to count total values in followers. However, what i know is that firebase do not have such a function to count and you need to manually do it.
From below i can see all the user data such as username and email. However, i still cannot figure out how to count the number of followers.
I hope someone can help. Thank you.
const ref = firebaseDB.ref();
ref
.child("Users")
.orderByChild("email")
.equalTo(this.state.currentUserEmail)
.once("value", snapshot => {
let userData = {};
for (var childSnapshot in snapshot.val()) {
userData.key = childSnapshot;
// then loop through the keys inside the child object and get the values like price (key) : 44.95 (value)
for (var value in snapshot.val()[childSnapshot]) {
console.log(value);
console.log(snapshot.val()[childSnapshot][value]);
userData[value] = snapshot.val()[childSnapshot][value];
}
}
console.log(userData);
});
Something like this should do the trick:
const ref = firebaseDB.ref();
ref
.child("Users")
.orderByChild("email")
.equalTo(this.state.currentUserEmail)
.once("value", snapshot => {
snapshot.forEach((childSnapshot) => {
console.log(childSnapshot.child("followers").numChildren());
}
console.log(userData);
});
The changes/additions:
Use DataSnapshot.forEach() for a cleaner way to loop over the children.
Use DataSnapshot.child() to get the snapshot for the followers node.
Use DataSnapshot.numChildren() to determine the number of followers.