Using ReactJS and firebase, I’m trying to create a new document with sub-collections, so I need (I believe) to get the id of the document in order to reference the correct path to add the sub collections :
JavaScript
x
14
14
1
function App() {
2
3
const usersCollectionRef = collection(db, "users");
4
5
useEffect(() => {
6
const migrateData = async () => {
7
await addDoc(usersCollectionRef, {});
8
var id = snapshot.docs.map((doc) => ({id: doc.id, doc.data()})); // note sure about this
9
const usersSubCollectionRef = collection(db, "users/{doc.id}/general_info"); // something like that
10
};
11
migrateData();
12
}, []);
13
}
14
Here is my Firestore :
I created the collection “general_info” manualy, I’m trying to do it with code.
Advertisement
Answer
The addDoc()
returns a DocumentReference that has ID of newly created document. Try refactoring the code as shown below:
JavaScript
1
4
1
const { id } = await addDoc(usersCollectionRef, {});
2
3
const usersSubCollectionRef = collection(db, `users/${id}/general_info`);
4