I'm trying to retrieve a sub collection from firestore database using Angular. I have collection 'Company' containing fields 'Name' and 'Id' and subcollection 'CustomerList' containg fields 'Name' and 'Id'
To retreive Company collection I have code:
private companyCollection: AngularFirestoreCollection<Company>;
getCompany() {
return this.company=
this.companyCollection.snapshotChanges().pipe(
map(changes => {
return changes.map(a => {
const data = a.payload.doc.data() as Company;
return data;
});
My question is how to retreive 'CustomerList' sub collection and add it to 'Company' object.
Here are 2 things:
Before you check you need to define relations between your customers and companies.
interface customer {
id: any;
name: string;
}
interface Company {
id: any;
name: string;
customerList: customer[];
}
Here is very simple example:
const customers = [
{
id: 0,
name: 'lilu',
},
{
id: 1,
name: 'lilu1',
},
{
id: 2,
name: 'lilu2',
},
{
id: 3,
name: 'lilu3',
}
];
const companies = [
{
id: 0,
name: 'lilu Company',
},
{
id: 1,
name: 'lilu1 Company',
},
{
id: 2,
name: 'lilu2 Company',
},
{
id: 3,
name: 'lilu3 Company',
},
];
let customersWithCompanies = [];
for (let item of companies) {
let obj = {
id: item.id,
name: item.name,
customerList: customers
};
customersWithCompanies.push(obj);
}
console.log(customersWithCompanies);
If this is collection prototype you need js/ts functions to get, set specific data and then push to firebase;
In this case you need to fetch data from different collections here is part of code from documentation.
From firebase documentation you need to define it like this:
import { doc } from "firebase/firestore";
const alovelaceDocumentRef = doc(db, 'users/alovelace');
Please view followin url: https://firebase.google.com/docs/firestore/data-model#web-version-9_2
If I didn't catch subject well please wite a comend and I'll make answer more clear with examples.