简体   繁体   English

firebase firestore v9 中的访问子集合

[英]access subcollection in firebase firestore v9

I'm trying to access the firebase firestore documents inside subcollection (messages):我正在尝试访问子集合(消息)中的 firebase firestore 文档:

user > user.uid > messages > docRef.id > date: Date.now()
                                         text: userText
                  userEmail: user.email
                  userName: display.name

I used the following:我使用了以下内容:

const snapRef2 = collection(db, "users/" + user.uid + "/messages")
onSnapshot(snapRef2, (snapshot) => {
    snapshot.forEach((doc) => {
        console.log(doc.data());
    })
})

But this method works only when user.uid is a string like: const snapRef2 = collection(db, "users/randomstring/messages")但是这种方法只有在 user.uid 是一个字符串时才有效: const snapRef2 = collection(db, "users/randomstring/messages")

How do I access the documents inside messages?如何访问消息中的文档?

const snapRef2 = collection(db, `users/${user.uid}/messages`) 

Make sure to use back ticks instead of quotation marks确保使用反引号而不是引号

The code in your answer works if you want to retrieve the messages for a specific user, identified by user.uid .如果您要检索由user.uid标识的特定用户的消息,则答案中的代码有效。

If you want to get the messages for all users, you can use a collection group query .如果要获取所有用户的消息,可以使用集合组查询 Such a query reads from all collections with a specific name, like messages :这样的查询从所有具有特定名称的 collections 中读取,例如messages

const snapRef2 = collectionGroup(db, "/messages")
...

The rest of your code can stay the same.您的代码的 rest 可以保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM