繁体   English   中英

React.js 如何在 Firestore 中获取子集合数据

[英]React.js how can i get subcollecion datas in firestore

这是一个基本问题。 我可以在用户自己的集合中为每个用户添加数据。 (用户/用户 ID/备注)。 我如何从这个子集合中获取数据? 我阅读了一些关于 ref.parent.parent.id 的信息,但我无法理解。 你能帮助我吗 ?

我的 addNewNote 函数代码:

const uid = auth.currentUser.uid;
const notesRef = database.collection("users").doc(uid).collection("notes");


 const addNewNote = async (newNote) => {
    await notesRef.add({
      note: {
        title: newNote.title,
        content: newNote.content,
      },
    });
  };

我的主页(也应该在此处显示注释):在这里,我知道 ->>> “database .collection("users") .doc(uid) .collection("notes") .onSnapshot((querySnapshot)" --->这是错误的,我需要像 parent.parent.id 或类似的东西那样做,但我无法理解。

<div className="home">
        {database
          .collection("users")
          .doc(uid)
          .collection("notes")
          .onSnapshot((querySnapshot) => {
            querySnapshot.forEach((doc, index) => {
              <Note
              key={index}
              id={index}
              title={doc.data().title}
              content={doc.data().content}
              onDelete={deleteNote}
            />
            });
          })}
      </div>

同样在这里,我在 firestore 中上传了一张图片。 在此处输入图片说明

这是我的应用程序截图(没有 firebase,只有一个数组),我用 map 函数读取它们。

没有firebase,这里是数组的代码:添加注释:

setNotes((prevNotes) => {
      return [...prevNotes, newNote];
    });
  };

使用 <Note/ > 阅读笔记:

{notes.map((noteItem, index) => {
              return (
                <Note
                  key={index}
                  id={index}
                  title={noteItem.title}
                  content={noteItem.content}
                  onDelete={deleteNote}
                />
              );
            })}
  

在此处输入图片说明

您可以使用安全规则来确保用户只能读/写他们自己的笔记。

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userID}/notes/{noteID} {
      allow read, write: if request.auth.uid == userID;
    }
  }
}

变量 userID 和 noteID 是通配符,这意味着它们将占用正在访问的资源路径的值。

要查询当前用户的笔记,您可以使用相同的查询。

const notesRef = database.collection("users").doc(uid).collection("notes") 
notesRef.get().then(notesSnapshot => {
  console.log(`${notesSnapshot.size} notes fetched!`)
})

我使用 reactfire 解决了这个问题。 它有很大帮助。 谢谢

暂无
暂无

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

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