Firestore获取子集合父文档ID-JavaScript

时间:2020-04-03 11:51:29

标签: firebase google-cloud-firestore

我的Firestore数据库中具有以下结构:几个UserLists集合,其中包含Users。每个用户可能有一个Notes子集合。

我正在做一个效果很好的子集合组查询,从Notes子集合中返回注释。

我的问题是,从Notes子集合中检索的Note文档中,我可以获得父文档ID吗?在下面的示例中,该用户为User 1。使用JavaScript。

Collection: UserList 1
  Doc: User 1
    Subcollection: Notes
      Doc: Note 1

Collection: UserList 2
  Doc: User 1
    Subcollection: Notes
      Doc: Note 1

1 个答案:

答案 0 :(得分:2)

您可以使用以下方法之一:

  const query = ......;
  query
    .then(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
        console.log(doc.ref.path);
        console.log(doc.ref.parent.parent.id);
      });
    })

在每个QueryDocumentSnapshot上,您可以使用ref属性,该属性返回一个DocumentReference。然后,在此DocumentReference上使用path属性,该属性将返回完整路径,例如UserList1/User1/Notes/Doc1

或者您使用DocumentReference的{​​{3}}属性,该属性返回一个parent,然后再次使用CollectionReference的{​​{3}}属性时间)以获取父项DocumentReference,然后获取该父项id的{​​{1}}属性。

相关问题