Home > Enterprise >  add document and subcolletion as batch write firebase and VUEJS
add document and subcolletion as batch write firebase and VUEJS

Time:09-02

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()
}

CodePudding user response:

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);
})
  • Related