【问题标题】:Angularfire2 Firestore Query with reference's ID带有参考 ID 的 Angularfire2 Firestore 查询
【发布时间】:2019-01-16 00:47:34
【问题描述】:

我是 Firebase 的新手,对 Angular 有基本的了解。这是我的学习示例项目。

我的 firestore db 有三个集合 - 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)
            }

我的打字稿类变量id 中有值pid1。需要查询与此父级关联的所有子级。我的努力到此结束,这不起作用,

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
)

大多数博客/SO 答案都解释了对内部集合的查询,而不是这个。

编辑 1:

感谢@ricardo-smania 指导我。这是直接的解决方案

使用 AngularFirestore.doc() 方法创建了对 id = 'pid1' 的父项的引用,并在 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
)

这只会获取给定parentparent_child 集合。 但我仍然不确定如何访问子属性

【问题讨论】:

  • 我是否正确地解释为您正在尝试查询所有 parent_child 文档以查找具有与给定 ID 匹配的 parent 属性值的文档?
  • 是的@joseph-webber,这就是我对这个查询的意思。我最终需要的是获取与该父级关联的所有子级的属性

标签: angular firebase angularfire2


【解决方案1】:

如果您在 Firestore 中使用“引用”字段类型,我相信您需要创建对记录的引用,然后使用此引用进行查询,例如使用 Firebase JS SDK 的示例:

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

但我不确定是否可以使用 AngularFire。但是您始终可以使用 this.db.firestore 回退到 vanilla SDK。

【讨论】:

  • 试过这个const pRef=this.db.doc('parent/'+id); this.db.collection&lt;any[]&gt;('parent_child', ref =&gt; ref.where('parent', '==', pRef)) .valueChanges().subscribe( data =&gt; console.log(data) ) 得到错误:Query.where() 调用了无效数据。不支持的字段值:自定义 AngularFirestoreDocument 对象
  • @RamanujanR 我刚刚遇到了同样的问题,但是如果您在文档上使用.ref,它应该可以工作。像这样:const pRef=this.db.doc('parent/'+id).ref;
猜你喜欢
  • 2018-07-07
  • 1970-01-01
  • 1970-01-01
  • 2022-10-08
  • 2018-06-27
  • 1970-01-01
  • 1970-01-01
  • 2020-12-16
  • 2018-10-25
相关资源
最近更新 更多