如何在Firestore中基于子集合文档值返回父集合? [英] How to return parent collection based on subcollection document value in Firestore?
问题描述
我的Firestore中有此收藏集:
I have this collection in my Firestore:
Collection: Team1
Document: TeamName
Subcollection: Notes
Subcollection: Users
Document: user1 => Field: name: "Anna", uid: "someID"
Document: user2 => Field: name: "John", uid: "someID"
让我们想象一个场景,其中有许多具有以上模式的Team集合.如何根据文档(在用户"子集合中)中的名称"字段使用JavaScript返回整个Team集合(这样我就可以访问例如Notes).
Lets imagine a scenario in which there are many Team collections with the schema above. How to return the whole Team collection with JavaScript (so I can access for example Notes) based on the Name field in Document (in Users subcollection) .
我尝试过:
var nameRef = db
.collection('Team1')
.doc('TeamName')
.collection('Users')
.where('name', '==', 'Anna')
const getData => ()=> {
nameRef.get().then((snapshot) => {
snapshot.docs.forEach((doc) => {
console.log(doc.data())
})
})
}
但是,上面的代码仅输出用户文档中的文档字段(名称,uid).
However the code above outputs only the document fields in the User Doc (name, uid).
推荐答案
除了 .data()
方法之外,检索到的 doc
也具有包含CollectionReference的.parent
属性-在这种情况下,它将引用您的 Users
集合.该集合还具有一个 .parent
属性,该属性将指向您的 TeamName
文档.它的父项将指向您的 Team1
集合.
In addition to the .data()
method, the retrieved doc
also has a .parent
property which contains a CollectionReference - in this case, it'd reference your Users
collection. That collection also has a .parent
property that will point to your TeamName
document. It's parent will point to your Team1
collection.
使用这些文档和集合的父属性,您可以将树向上"移动到团队集合中,以在其上检索其文档.
Using these parent properties of the documents and collections, you can work your way 'up' the tree to your Team collection upon which you can retrieve its documents.
这篇关于如何在Firestore中基于子集合文档值返回父集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!