I’m using firebase + Angular.
I need to access data from a collection (orcamentosRecebidos) that is within another collection (Projects), the collection (orcamentosRecebidos) contains several documents. I need to loop through all documents within (Projects), access the sub-collection (orcamentosRecebidos) within each project, and loop through all documents contained in the collection again, making a comparison, comparing the "id" contained within of each document with the id of the logged in user (which in this case is in the storage in the browser).
I need this query to return all documents in which the "id" of the collection is equal to the user’s id (the "id" property is within each document! I’m not talking about the document’s id).
Here are some images from firestore to better illustrate.
First access the "Projects" collection, then loop through all the documents and access the "orcamentosRecebidos" collection for each of the documents.
After that, make a new loop through each of the documents within the "orcamentosRecebidos" collection and return the documents that have the "id" property equal to the "id" of the logged in user.
my firebase imports:
import { Firestore } from ‘@angular/fire/firestore’;
import { collection, query, where, getDocs, doc, getDoc } from ‘firebase/firestore’;
I use the Angular/Fire library for some queries.
I tried this query with several different scripts, all without success, I think I’m missing something along the way…
async pegarOrcamentosDoUsuario() {
const q = query(collection(this.firestore, "projects/orcamentosRecebidos"), where("id", '==', localStorage.getItem('app_auth')));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
console.log("id doc:", doc.id, " => ", doc.data());
})
}
Can someone help me??
2
Answers
I received the following error:
When I try to use the code according to the documentation there are hundreds of errors in my code. Here are my firebase references:
in the component:
I use the official angular/fire library.
So I use this.firebase to reference my database. When I try to import "npm install firebase-admin --save" as it says in the documentation, to use (const db = getFirestore();) I get several errors...
You’re querying
collection(this.firestore, "projects/orcamentosRecebidos")
, but no such path exists in your database screenshots.You’ll need to specify the full path to the collection you want to query (so
collection(this.firestore, "projects/p2GmsCMmHUImtUGJHuf/orcamentosRecebidos")
), or alternatively you can use a collection group query to query allorcamentosRecebidos
collections.