How can I get from firebase array of objects - javascript

I need to get array of objects of sources from firebase grouped by category.
Firebase structure is:
enter image description here
Every authenticated user have its own array of sources.
Security rules for db is:
enter image description here
Every source have array of articles and have category.
I use vuefire to bind to firebase-database. I have written this, but I don't know what I should do next to get all sources grouped by category.
var sources=[];
var db=firebase.database();
var id=auth.user().uid;
var userDb=db.ref(id);

Maybe you can imagine how to retrieve your data from firebase database if I give you this example:
function getData(data) {
var items = data.val();
console.log(items, 'myItem') //here is your items that you need
}
function errData(err) {
console.log('error:', err)
}
const id = firebase.auth().currentUser.uid;
const result = firebase.database().ref(id);
result.on('value', getData, errData)

Related

here is my firebase datastructure. how to fetch user data and make table in html

This is the database structure i have i want to get logged in user data.
i want to make table of data: Columns: Date,Status
Also i want to make percentage piechart wheel by calculating success and failure rate. but not able to get data from firebase.
I tried this but not working. I'm able to log in log out successfully. I'm also able to add data in firebase only once per date.
I'm just not able to fetch and show in table.
Here's what i tried:
`
// Get the user's attendance records
firebase.database().ref("attendance").once("value", function(snapshot) {
// Get the attendance data
var attendanceData = snapshot.val();
var userId = firebase.auth().currentUser.uid;
// Display the attendance history
for (var email in attendanceData) {
var attendance = attendanceData[email][userId];
if (attendance) {
for (var date in attendance) {
var status = attendance[date].status;
var tr = document.createElement("tr");
tr.innerHTML = `<td>${date}</td><td>${status}</td>`;
attendanceHistoryTable.appendChild(tr);
}
}
}
});
If I understand correctly, you have a data structure like this:
attendance: {
user: {
"$uid": {
"$date": {
Status: "..."
}
}
}
}
And from this you want to show the status per date for the current user.
If that's indeed the use-case, you can do this with:
const userId = firebase.auth().currentUser.uid;
const attendanceRef = firebase.database().ref("attendance");
const userRef = attendanceRef.child("users").child(userId);
userRef.once("value", function(userSnapshot) {
userSnapshot.forEach((dateSnapshot) => {
const status = dateSnapshot.child("Status").val();
console.log(`User: ${userSnapshot.key}, Date: ${dateSnapshot.key}, Status: ${status}`);
... // TODO: add the data to the HTML as you're already doing
});
});
The main changes I made here:
This only loads the data for the current user, instead of for all users.
This code uses the built-in forEach operation of a DataSnapshot.
This code gives more meaningful names to the variables, so that it's easier to parse what is going on.
This code uses "Status" rather then status, since that's the key in your database screenshot too.

Document reference in firestore using react-native(javascript)

Document Reference is used to get document field and its collections from firestore. Following are some examples:
1. Function to read data from field which is having docRef
[Firestore schema]: https://i.stack.imgur.com/pEPK5.png
Here in collection people there is doc named user1 which have a field named hlpr which have docRef for user2 so if i want to access that docRef data i will use following code:
function foo4() {
var user1 = db.collection('people').doc('user1')
user1.get().then((data) => { //get user1 whole doc using get()
var t = data.get('hlpr') //choose field 'hlpr'
t.get().then((doc) => { //get 'hlpr' data() from get()
var user2 = doc.data() //get whole doc from user2
console.log(user2.name) //output field 'name' from user 2
})
})}
2. Read data from array from of docRef. In previous image you can see field named 'cts' which is having array of docRef. Code:
function foo3() { //function to get data from array of docRef
var user1 = db.collection('people').doc('user1'); //choose user1 doc
user1.get().then((doc) => { //get data() of user1 using get()
var contacts = doc.get('cts'); //set var k to field 'cts'
contacts.forEach((data) => { //for each item in array field cts
var userx = data.get(); //read data() using get()
userx.then((doc) => {
var frnd = doc.data(); //set frnd to each data we get from doc
console.log(frnd.name) //output their any field value here i have chosen name
});
});
})}
NOTE: Above code works correctly and you can also use data to put into array also above code might not be best way to get data, but i am a beginner so this is the best i could do.
You can break your code down to a chain of awaits per the comments but a promise chain if processing one item can be fairly clean.
async function foo4() {
var user2 = await db.collection('people').doc('user1').get()
.then(data => data.get('hlpr'))
.then(doc=> doc.data())
.finally(result => result)
.catch(console.log());
you can do some clean code when you nest promise chains.
The second code block has potential errors, if your client exceeds pending 50 documents the client modules will throw errors and fail reads.

How to pass data of an object to HTML file

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

how to update a map FIRESTORE value with a key JAVASCRIPT

collection name user and a collection name query.
each user document holds a map name seenQueries with string (queryID) : number.
given a user and a queryID (key) i wish to update its number (the value). the rest of the documents fields should remain untouched.
function updateQuerySeen(userID, queryId) {
var userRef = db.collection("users").doc(userID);
var queryRef = db.collection("query").doc(queryID);
const promise1 = userRef.get();
const promise2 = queryRef.get();
Promise.all([promise1, promise2]).then((values) => {
doc1 = values[0];
doc2 = values[1];
curMsgArrayLen = doc2.data().msgArrayLen;
// Uupdate seenQueries map key:queryID
userRef.update({
seenQueries.queryID: curMsgArrayLen; // DOESN'T SEEM TO WORK
}).then(function () {
//console.log("setDocument);
})
.catch(function (error) {
console.error("UPDATE user's seen query failed ", error);
});
});
looked at google API, but it doesn't seem to work https://firebase.google.com/docs/reference/rules/rules.Map
saw this answer Update individual map in cloud firestore document but wasn't sure which one fits my objective, and this one How to update fields in Firestore map didn't work
thank you!

Checking data in deep array with includes (Firebase retrieve data JS)

So I am new to the Firebase database and what I like about it is that I don't have to build a whole backend for just storing some simple data. What I am trying to do is pushing data to an array that I like to recieve from firebase. Then after that I would like to check if the email that was filled in, is included in the data from the firebase database. But because it's firebase and it has multiple arrays, objects etc I don't know how to check that. So the flow is: User fills in data, Applications makes a call to the firebase db and the Application is retrieving the current data from firebase. Then the Application will check if the data that is inputed is already there, and if so, will throw an alert that the data is already in the database. If not, the data will be submitted.
Also, I am wondering if this is the right way to retrieve data from the database:
Main.js
function writeUserData() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
firebase.database().ref('/aanmeldingen/').push({
username: name,
email: email,
});
var dbRef = firebase.database().ref().child('/aanmeldingen/');
dbRef.on('value', snapshot => {
const snap = snapshot.val();
const array = [];
array.push(snap);
console.log(array);
const res = array.includes(email);
console.log(res);
console.log(email);
});
}
Output in console
As you can see this returns multiple data. The include function will check on the submitted emailadress. This returns false even I had inputted "info#webpack.com". How can I check the right data object? It has to check all objects under "0" and return in the console if the submitted emailadress is already there.
I haven't tested it yet but i hope you get the idea. Also this is not the most efficient way to do this.
function ifEmailExist(arr,email){
var _t = 0;
for(var x in arr){
for(var y in arr[x]){
if(arr[x][y].email){
if(arr[x][y] === email){
_t++;
}
}
}
}
return _t;
}
Usage:
if(ifEmailExist(arr,"info#webpack.com") > 0){
//do stuff
}
You should use child_added instead of value. Whenever a new node is added in database, child_added will trigger and then you can take action on the data.
var dbRef = firebase.database().ref().child('aanmeldingen');
dbRef.on('child_added', snapshot => {
var username = snapshot.val().username;
var email = snapshot.val().email;
console.log(username);
console.log(email);
});

Categories