hadi tedi
hadi tedi

Reputation: 525

Firestore batch write using loops

I want to write batch date data using for loops but it didn't work though the console says otherwise. I think it's only updated in firebase console for the last iteration only. I have tried for 2 days and don't know what is what anymore !

const handleSubmit = e => {
e.preventDefault()
const stdRoom = firebase.firestore().collection("stdRoom").doc()
let i;
let momentDate = moment("June 7 2020").startOf("day")._d

for ( i=0 ; i<10 ; i++){
  stdRoom.set({avail: 7, date: momentDate })
  .then(function() {
    console.log("Document successfully written!");
  })
  .catch(function(error) {
    console.error("Error writing document: ", error);
  });

  momentDate = moment(momentDate).add(1,"d").startOf("day")._d
  console.log(momentDate)
}

I have tried batch() and commit after exiting loop but no avail. Im using momentjs for date handling. If I do one by one then it worked.

It's a hotel room. I want to set availability for a std room for 10 days in this case with availability of 7 for each day and maybe 365 days. Any solution please? Thanks in advance.enter image description here

Upvotes: 2

Views: 872

Answers (1)

Grant Singleton
Grant Singleton

Reputation: 1651

You are writing to the same document:

const stdRoom = firebase.firestore().collection("stdRoom").doc()

In a for loop:

for ( i=0 ; i<10 ; i++)
  stdRoom.set({avail: 7, date: momentDate })

Firestore limits document writes to 1 per second and this for loop will violate that restriction. See Writes and Transactions here

Upvotes: 3

Related Questions