It's a basic question. I can add data for each user in on users own collection. (users/user-id/notes). How can i get datas from this subcollection? I read some informations about ref.parent.parent.id, but i can't get it. Can you help me ?
my addNewNote function codes:
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,
},
});
};
my homepage (also notes should seems here): Here, I know ->>> "database .collection("users") .doc(uid) .collection("notes") .onSnapshot((querySnapshot)" ---> this is wrong, i need to do like parent.parent.id or something like that, but i can't get it.
<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>
Also here i have uploaded an image in firestore.
Here my app screenshot (without firebase, with just an array), and i read them with map function.
without firebase, here codes for array: Adding note:
setNotes((prevNotes) => {
return [...prevNotes, newNote];
});
};
Reading note with <Note/ >:
{notes.map((noteItem, index) => {
return (
<Note
key={index}
id={index}
title={noteItem.title}
content={noteItem.content}
onDelete={deleteNote}
/>
);
})}
You can use security rules to make sure user can read/write their own notes only.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userID}/notes/{noteID} {
allow read, write: if request.auth.uid == userID;
}
}
}
The variables userID and noteID are wildcards that means they'll take up value of resource path being accessed.
To query the notes of current user, you can use the same query.
const notesRef = database.collection("users").doc(uid).collection("notes")
notesRef.get().then(notesSnapshot => {
console.log(`${notesSnapshot.size} notes fetched!`)
})
I solved this problem with using reactfire. It helps a lot. Thanks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.