1

I am trying to do batch write. My goal:

  1. First I want to write data which generate new collection with unique ID.
  2. Then I want to add to this unique collection a subcollection of list by running forEach.

Current problem:

  1. I don't know how to get this unique ID which is generated when first batch runs which I then want to parse in second batch where I create subcollection.
  2. forEach doesn't work it only takes the last item from list orders.

this is my current code, note I use VUEJS3 with Pinia and for Firebase Web version 9.

      orders: [
        {
          id: 'id1',
          product: 'yup',
          productivity: 'nothing',
          quantity: 'lot',
        },
        {
          id: 'id2',
          product: 'Smith',
          productivity: 'huge',
          quantity: 'few',
        },
      ],
const batch = writeBatch(db);

addOrderTest() {
  const storeAuth = useStoreAuth();
  const docRef = doc(collection(db, 'users', storeAuth.user.id, 'clients', 'punTa54ogJ6wLgRmAp4Y', 'ordera'))

  batch.set(docRef, {name: 'something'})

  // here I want to add list Orders in collection which I make above, but I don't know how to get this newId, and also forEach takes only last item from table //  
  const newId = docRef.id
  this.orders.forEach((order) => {batch.set(newId, order)})


  return batch.commit()
}
BeEmil
  • 61
  • 6

1 Answers1

1

You can first create a DocumentReference for the parent document before the batch.set() statement and then use the new doc ID as shown below:

const docRef = doc(collection(db, 'users', 'storeAuth.user.id', 'clients', 'punTa54ogJ6wLgRmAp4Y', 'ordera'));

batch.set(docRef, {
  name: 'something'
})

const newId = docRef.id; 
// use this ID in DocumentReference of order documents

this.orders.forEach((order) => {
  const orderRef = doc(collection(db, 'users', storeAuth.user.id, 'clients', 'punTa54ogJ6wLgRmAp4Y', 'ordera', newId, 'order'))
  batch.set(orderRef, order);
})
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • It throws me an error: Uncaught FirebaseError: Provided document reference is from a different Firestore instance. – BeEmil Sep 01 '22 at 12:58
  • @BeEmil can you update your question with the latest code that you have? – Dharmaraj Sep 01 '22 at 13:11
  • I just updated question. maybe you also now what is wrong with 2nd batch command when I run forEach it only takes 2nd item. – BeEmil Sep 01 '22 at 13:29
  • @BeEmil the `batch.set()` takes a `DocumentReference` as first arg but you were passing the ID itself. Can you try the code in my updated answer? – Dharmaraj Sep 01 '22 at 13:32