'ReactJS/Firestore: how to get the id of a newly created document
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 :
function App() {
const usersCollectionRef = collection(db, "users");
useEffect(() => {
const migrateData = async () => {
await addDoc(usersCollectionRef, {});
var id = snapshot.docs.map((doc) => ({id: doc.id, ...doc.data()})); // note sure about this
const usersSubCollectionRef = collection(db, "users/{doc.id}/general_info"); // something like that
};
migrateData();
}, []);
}
Here is my Firestore :
I created the collection "general_info" manualy, I'm trying to do it with code.
Solution 1:[1]
The addDoc() returns a DocumentReference that has ID of newly created document. Try refactoring the code as shown below:
const { id } = await addDoc(usersCollectionRef, {});
const usersSubCollectionRef = collection(db, `users/${id}/general_info`);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharmaraj |

