Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I created the collection "general_info" manualy, I’m trying to do it with code.

>Solution :

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`);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading