0

Following code inserts data into the 'doctors' collection in firestore. But I want to add the same data records into another collection named 'next' in the same firestore database simultaneously.

service.ts

create_Newdoctor(Record){
  return this.firestore.collection('doctors').add(Record);
}

component.ts

CreateRecord(docForm: NgForm){
  let Record = {};
  Record['fullName']=this.fullName;
  Record['email']=this.email;
  Record['gender']=this.gender;
  Record['role']="doctor";

  this.DoctorService.create_Newdoctor(Record).then(res=> {
    this.fullName="";
    this.email="";
    this.gender="";
    console.log(res);
        this.message = "New doctor added";
  }).catch(error=>{
    console.log(error);
  });
}

Can you please tell me a way to do this.Thank you in advance.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
pghasandi
  • 19
  • 7
  • You will want to use a batch write. https://stackoverflow.com/questions/47268241/angularfire2-transactions-and-batch-writes-in-firestore – Doug Stevenson Jun 26 '20 at 21:53

1 Answers1

0
const collections = ["doctors", "next"];

create_Newdoctor(Record, collections) {
  const promises = collections.map(collectionName =>
    this.firebase.collection(collectionName).add(Record)
  );

  return Promise.all(promises);
}
  • You can have as many collections in the collections array. I just included 2 as per your requirement. – Aishwarye Chauhan Jun 26 '20 at 20:05
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Dharman Jun 28 '20 at 22:01