Firestore获取子集合父文档ID-JavaScript [英] Firestore get subcollection parent document ID - JavaScript

查看:45
本文介绍了Firestore获取子集合父文档ID-JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following structure in my Firestore DB: several UserLists collections, which hold the Users. Each user may have a Notes subcollection.

我正在做一个效果很好的子集合组查询,从整个Notes子集合中返回笔记.

I'm doing a subcollection group query that works well, returning notes from across the Notes subcollection.

我的问题是,从Notes子集合中检索到的Notes文档中,我可以获得父文档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

推荐答案

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

You could use one of the following approaches:

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


在每个 QueryDocumentSnapshot 上,您可以使用 path 属性,它将返回完整路径,例如 UserList1/User1/Notes/Doc1 .


On each QueryDocumentSnapshot, you can use the ref property, which returns a DocumentReference. Then, on this DocumentReference you use the path property, which will return the full path, e.g. UserList1/User1/Notes/Doc1.

或者您使用 parent DocumentReference 的> 属性,该属性返回 parent 属性(这次是 CollectionReference 的属性),以获取父 DocumentReference ,然后此父 DocumentReference id 属性.

Or you use the parent property of the DocumentReference, which returns a CollectionReference, then you use again the parent property (of the CollectionReference this time) to get the parent DocumentReference and then the id property of this parent DocumentReference.

这篇关于Firestore获取子集合父文档ID-JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆