Ramanujan R
Ramanujan R

Reputation: 1719

Angularfire2 Firestore Query with reference's ID

I'm new to Firebase and have basic knowledge in Angular. This is my sample project for learning.

My firestore db has three collections - parent, children, parent_child

parents :
    pid1 - { name: Parent1 }
    pid2 - { name: Parent2 }

children:
    cid1 - { name: Child1 }
    cid2 - { name: Child2 }

parent_child:
    pcid1 - { 
              parent: /parents/pid1  //(a reference to Parent1)
              child: /children/cid2  //(a reference to Child2)
            }

I have the value pid1 in my typescript class variable id. Need to query all children associated with this parent. My effort ended here, which is not working,

constructor(private db: AngularFirestore) { }

let id = 'pid1';
this.db.collection<any[]>('parent_child', ref => ref.where('parent.id', '==', id))
.valueChanges()
.subscribe(
   data => console.log(data) // Prints empty array
)

Most of the blogs/SO answers explains querying on inner collection, not this.

EDIT 1:

Thanks @ricardo-smania for directing me. This is the immediate solution

Created a reference to the Parent with id = 'pid1' using AngularFirestore.doc() method and used AngularFirestoreDocument.ref property in where clause.

constructor(private db: AngularFirestore) { }

const id = 'pid1';
const pObj = this.db.doc('parents/'+id);
this.db.collection('parent_child', ref => ref.where('parent', '==', pObj.ref))
.valueChanges()
.subscribe(
   data => console.log(data) // Prints the array with references
)

This only fetches the parent_child collection for the given parent. But still I'm not sure how the children properties are accessed

Upvotes: 4

Views: 3851

Answers (1)

Ricardo Smania
Ricardo Smania

Reputation: 3139

If you are using a field type "Reference" in Firestore, I believe you need to create a reference to the record and then query using this reference, like this example using the Firebase JS SDK:

const ref = firebase.firestore().collection('parents').doc('pid1');
const parentChild = await firebase.firestore().collection('parent_child').where('parent', '==', ref).get();

But I'm not sure if that's possible using AngularFire. But you can always fallback to the vanilla SDK by using this.db.firestore though.

Upvotes: 4

Related Questions