Home > other >  angular batch update not working to firebase
angular batch update not working to firebase

Time:10-14

I've created a multidimensional array called newOrder:

0: {id: 'JNuxJewf4E8YyX7t3fPk', order: 2000}
1: {id: 's2kCZnF5vhp1E6cW3VXI', order: 3000}
2: {id: 'UGPPNa7zTuUkBmuorF2v', order: 4000}
3: {id: '0YzyArRPQQ3ZyAOfOJjM', order: 5000}
4: {id: 'LpZnzX6NufWsaVQ52lyS', order: 6000}
5: {id: 'VfL8pX77LCxXniWQunk7', order: 7000}
6: {id: '8QtF3CbpVjIXeI4ziHxy', order: 8000}
7: {id: 'y05y6Hta6kesXymg034Q', order: 9000}
8: {id: 'LQPq6q3Dp6CeACTiO8IC', order: 10000}
9: {id: 'bmeT3h3kG7Oeilf0nIQ8', order: 11000}
10:{id: 'mrHFK2wEsn9UhFz5AOEQ', order: 12000}

I'm trying to cycle through them and update the order: field in each record with id:. So far I've read that a batch update is the way to go. So I've written the following:

const batch = this.fireStore.firestore.batch();
this.newOrder.forEach((val, index) => {
  const id = this.newOrder[index]['id'];
  const orderNum = this.newOrder[index]['order'];
  console.log (' id:'   id   ' order:'   orderNum);
  const pageRef = this.fireStore.doc('content/${id}').ref;
  batch.update(pageRef, {order:orderNum});
});

I'm getting no errors and the console log is outputting correctly, but it's not updating the firebase records. What am I doing wrong? I've been at this for 2 days now.

CodePudding user response:

From your code it seems that you miss the call to commit(). This asynchronous method returns a Promise resolved once all of the writes in the batch have been successfully written to the backend as an atomic unit.

const batch = this.fireStore.firestore.batch();
this.newOrder.forEach((val, index) => {
  const id = this.newOrder[index]['id'];
  const orderNum = this.newOrder[index]['order'];
  console.log (' id:'   id   ' order:'   orderNum);
  const pageRef = this.fireStore.doc(`content/${id}`).ref;
  batch.update(pageRef, {order:orderNum});
});
batch.commit()
.then( => {  // ... If necessary  });
  • Related