Home > Blockchain >  add collection and batch add documents with firebase
add collection and batch add documents with firebase

Time:06-21

I have a screen on my app where a user inputs a number {x} and from this number I would like to create a collection in the programs doc and then add {x} documents to the collection.

Only one document gets added to the collection.

const handleContinue = async () => {
    const batch = writeBatch(db);
    const blockArray = [...Array(blockCount).keys()];
    // use the program name as the ID.
    const docRef = doc(db, `Users/${userStore.uid}/programs/${programName}`);

    const payload = {
      title: programName,
      units: programUnits,
      system: programSystem,
      status: programStatus,
      days: dayCount,
      blocks: blockCount,
    };
    await setDoc(docRef, payload, { merge: true });
    const docSnap = await getDoc(docRef);

    if (docSnap.exists()) {
      const dRef = doc(db, `Users/${userStore.uid}/programs/${programName}`);
      const cRef = collection(dRef, "blocks");

      blockArray.forEach((index) => {
        const insert = doc(cRef, `block_${index}`);
        batch.set(insert, { name: `Block ${index}` });
      });

      await batch.commit();
    }
 };

Structure I'm expecting starting from programs doc

-programs (doc)

-- programs fields

-- blocks (collection) <-- known collection name

--- block_1 (doc)

--- block_2 (doc)

--- block_3 (doc)

...etc

block_1, block_2 etc would be the document ID.

CodePudding user response:

As far as I can see in the code you're writing multiple documents, but all to the same collection: Users/${userStore.uid}/programs/${programName}/blocks.

If you want to create multiple collections, you'll need to vary one of the odd-indexed parameters in this path, like blocks_1, blocks_2, etc. Note though that this is not recommended in most scenarios, as the client-side SDKs have no way to request a list of the collections under a specific path, so it's typically best to use hard-coded collection names - or collection names that are implicitly known in some other way.

CodePudding user response:

So I found that my array I was looping over wasn't what I expected, nothing to do with Firebase. Fixed it further upstream and now I get the results I was after.

  • Related