Skip to content
Advertisement

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 :

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:

const { id } = await addDoc(usersCollectionRef, {});

const usersSubCollectionRef = collection(db, `users/${id}/general_info`);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement