[英]Angularfire2 Firestore Query with reference's ID
I'm new to Firebase and have basic knowledge in Angular. 我是Firebase的新手,并且具有Angular的基本知识。 This is my sample project for learning.
这是我的学习示例项目。
My firestore db has three collections - parent, children, parent_child 我的firestore数据库有三个集合-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
. 我的打字稿类变量
id
有值pid1
。 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. 大多数博客/ SO答案都说明了对内部集合的查询,而不是这个。
EDIT 1: 编辑1:
Thanks @ricardo-smania for directing me. 感谢@ ricardo-smania指导我。 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. 使用AngularFirestore.doc()方法创建对id为'pid1'的Parent的引用,并在where子句中使用AngularFirestoreDocument.ref属性。
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
. 这只会获取给定
parent
的parent_child
集合。 But still I'm not sure how the children properties are accessed 但是我仍然不确定如何访问children属性
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: 如果您在Firestore中使用字段类型“ Reference”,我相信您需要创建对该记录的引用,然后使用该引用进行查询,例如使用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. 但是我不确定使用AngularFire是否可行。 But you can always fallback to the vanilla SDK by using
this.db.firestore
though. 但是,尽管如此,您始终可以通过使用
this.db.firestore
退回到this.db.firestore
SDK。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.