I tried a lot of times but I am still not able to retrieve data from multiple documents, The below screenshot shows that I have 3 documents in my collection and my question is how to retrieve data from each of them.
I used foreach loop to loop through all the documents but I don't know how to retrieve data from id RoKQBRcuaVfcGPKNswbx or id Y8KbSQHcuxctJCJ1lWYH because it auto retrieve the data of the last id.
I really need your help, please.
Thank you.
The snapshot object contains all the 3 documents in your collection. You must iterate over all and render data to your HTML as explained below.
db.collection("Policies List").get().then((snapshot) => {
const documents = snapshot.docs //array of documents
documents.forEach((doc) => {
const docData = doc.data() //Data of that single document
console.log(docData)
renderToHtml() // Code that creates new HTML elements
})
})
This way you are creating new HTML elements for all the documents in your collection. The renderToHtml() function will contain that .innerHTML code.
Please make sure to see the logs in the console. They'll help understand the structure in a better way.
Related
I'm trying to access data from a firestore document, but I'm getting an error message that exercise.data() is not a function. I don't understand how the exercisesToAdd array is an array of documents, but I can't use .data() to get the contents of the items? How else would I go about getting the data from those documents?
I know the exercisesToAdd array is actually being filled with documents because I see them in the database when I send the array. Seems straight-forward but I must be missing something.
chosenExercises.forEach((exercise) => {
exercisesToAdd.push(doc(db, 'Users/' + auth.currentUser.uid + '/Exercises/' + exercise));
});
exercisesToAdd.forEach((exercise) => {
console.log(exercise.data());
});
As #Doug Stevenson stated in his comment:
Your code hasn't actually performed any queries, so there is no document data available. Please review the documentation and use get() to execute each document query first before calling data() on anything. All doc() does is create a DocumentReference, which doesn't contain any data.
I have recently implemented firebase into my project and I have created a user collection, this collection has a document for each user and each document has about 8 fields, when my user launches the app, I am trying to pull the document that corresponds to his data, so im doing the following query:
async function getUserData() {
const _collection = collection(db, "users")
const _query = query(_collection, where("userid", "==", uniqueUserID))
const querySnapshot = await getDocs(_query)
querySnapshot.forEach((doc) => {
console.log(doc.data())
})
setLoadingStatus(false)
}
This query works and gives me the corresponding user data, but the problem is, if the user is too far down the collection, this will execute 8 reads per document until it gets to the corresponding user, I have tried to implement a cache system using a lastModified but I still need to read the document data for that field and it will end up using more or less the same amount of reads. My question is: How do I reduce the amount of read operations that get executed when im trying to compare values in the documents, I have also thought of adding an a like so a_uniqueUserID so it gets ordered alphabetically and takes the first spot of the document but it's hacky.
EDIT: Here is what my structure looks like:
I think you are misunderstanding the definition of a document and a field. When you read a document, you always get all fields out of it. The snapshot contains everything read, even if you don't use it. There is no additional cost per field, other than the storage required to hold it all. In your screenshot, you show 5 documents, and one of those documents have 8 fields.
You are probably misunderstanding the metrics in the console. When you read and write documents using the console, those are also billed as reads and writes - use of the console is not "free". What you are seeing is a combination of what your app is doing in combination with what you're doing in the console.
Recently I came across a problem, I am making a function where you can get rid of chats in my app so I have this function
function deleteconvo() {
const me = firebase?.auth?.currentUser?.uid;
const members = [me, recipient.uid];
firebase.db.collection("conversations").remove({ members });
}
Firebase is telling me that:
firebase.db.collection("conversations").remove({ members }); is not a function
I also tried .delete and I cant find any answers online. Anyone have a solution to this?
note: I understand that I have to grab the docs value too, because I am in the conversation collection of the the database each conversation has its own unique ID, which I dont know how to grab and store that in a variable.
A good starting point is the official Firestore documentation regarding how to delete data.
In that page you can find examples in different languages on how to delete documents, fields and collections.
For example to delete an entire collection or subcollection in Cloud Firestore you need to retrieve all the documents within the collection or subcollection and delete them.
And to delete a document you can use the delete() method:
const res = await db.collection('cities').doc('DC').delete();
`
It this possible to do? After some research, I couldn't find a way to do it.
My "workaround" is to get all subCollection documents first, then retrieve their parent keys and retrieve again. But I believe there is a better way to do it.
let subDocs = await firestoreDb.collectionGroup('sub_collections').get()
let parentDocKeys = {};
subDocs.docs.forEach(async (element) => {
parentDocKeys[element.ref.parent.parent.id] = 1;
});
let result = await firestoreDb.collection('parentCollection').where(firestore.FieldPath.documentId(), 'in', Object.keys(parentDocKeys)).get();
return res.send(result.docs.map(x=>x.data()));
Firestore queries can only filter documents based on data in the document itself. There is no way to check data in any other documents, neither in the same collection, nor in other (sub)collections.
This means that it is not possible to retrieve only documents for which a subcollection exists without changing the data in the parent document. For example, if you update a field (say hasSubcollectionBla) in the parent document each time you add/remove to the subcollection, you can filter on the value of that field.
What you do with this is making the writing of data more complex, so that the read/query becomes easier and more scalable. This is a common trade-off when using NoSQL databases, such as Firestore.
I have data model like this
Players-->root collection
Sports--->root collection
Players_Sports---root collection
I want get all the sports(Multiple sport) details or document player belongs.
For this I am using angularFireStore5
First, I am getting
Player details like this
this.db.collection('players').doc(id).get().toPromise()
Second, I am getting Player(user) linked PlayerSport
db.collection<any>('PlayerSports',ref => ref.where('playerId', '==', id) ).get().toPromise()
Third, I am trying to get Sports details based on ID'S,
db.collection<any>('sportsType', ref => ref.where('sportsType' 'in' [sportsIDs])).get().toPromise()
where SportIDs is arrary of ID that are linked in player_sports
First and Second steps works fine, but third steps is not giving any data or response
Could you please let me know where is the problem,
is it in Data model or code? my guess is that data model is not correct. Please guide me on this.
I would suggest getting the data from firebase and storing it inside a list so the app can access it later.
void getDataF(){
databaseReference
.collection("TableName")
.getDocuments()
.then((QuerySnapshot snapshot) {
snapshot.documents.forEach((f) {
iDFacList.add(f.documentID);
dbFacList.add(f.data["FieldName"]);
});
});
}
There is no sportsType field in the sportsType document as far as I can see.
If you're trying to find documents based on their SportsId field, you'll want ref.where('SportsId'....
Update
It seems that you're trying to find a document by its ID, which you can do with:
ref.doc(sportsIDs)
If you want to get multiple documents, or get a single document as a collection, you can use:
ref.where(firebase.firestore.FieldPath.documentId() 'in' [sportsIDs])