Home > other >  ReactJS/Firestore: how to add sub-collection to existing firestore document
ReactJS/Firestore: how to add sub-collection to existing firestore document

Time:04-08

I'm trying to create a new collection in an existing firestore document :

Here is my firestore :

enter image description here

I'd like to create the "general" collection automaticaly.

Here is my code :

function App() {
  const dataGeneral = {
  email: "",
  firstname: "",
  lastname: "",
  phone: "",
  gdpr: false,
};

useEffect(() => {
  const migrateData = async () => {
    const usersCollectionRef = collection(db, "users"); //gets the root collection
    const { idUser } = await addDoc(usersCollectionRef, {}); // Creates a new document in the root collection

    const usersSubCollectionGeneralRef = collection(db,`users/${idUser}/general`); //Creates a sub collection in the just created document

    const { idGeneral } = await addDoc(usersSubCollectionGeneralRef, { dataGeneral }); //Creates a document in the newly created collection

   };
   migrateData();
  }, []);
}

CodePudding user response:

how to add sub-collection to existing firestore document

You don't add sub-collection explicitly, since Firestore cannot have empty collections. Instead sub-collections will be added automatically when adding a document to a collection. (And also deleted automatically if they don't hold any documents anymore)

That being said, your code destructures idUser and idGeneral from objects where those properties don't exist. You probably want to access the property id like this:

// Create a new, empty document in `users`
const usersRef = collection(db, 'users');
const user = awaitDoc(usersRef, {
  data: 'new document in users'
});

// Create a new document in sub-collection `general`
const generalRef = collection(db, `users/${user.id}/general`);
const general = awaitDoc(generalRef, {
  data: 'new document in sub-collection general'
});

Your intention might have been to rename the destructured property. If that's the case, see MDN for how to do that.

const {id: idUser } = await addDoc(...)
console.log('id of new document: ', idUser)
  • Related