Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

583
Views
How do we copy data from one collection to another in firestore

I am trying to copy data from one collection to another collection not sure what I am doing wrong or right I am trying to copy everything that is in "todo" with date equal to 2021-08-14 and copy it to "template" so far all I can to do is get the data from todo and print to console

const db = firebase.firestore();
const todoRefFrom = db.collection('todo');
const todoRefTo = db.collection('templates');

const todos = await todoRefFrom.get();
  todos.forEach(async doc => {
    console.log('set set', doc);
    todoRefTo.set(Map.fromEntries(doc.data().entries));
  });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Just query todo collection for documents having startDate as 14 August. Then just save all the documents to your new collection, in batches which is performance-wise better way.

    const db = firebase.firestore();
    const todoRefFrom = db.collection('todo');
    const todoRefTo = db.collection('templates');
    
    let startDate = new Date('2021-08-14');
    let endDate = new Date('2021-08-15');
    
    const todos = await todoRefFrom.where('dateField', '>=', startDate).where('dateField', '<', endDate).get();
    let writeBatch = firebaseAdmin.firestore().batch();
    let i = 0;
    for (let doc of todos.docs) {
        writeBatch.set(todoRefTo.doc(doc.id), doc.data());
        i++;
        if (i > 400) { // write batch only allows maximum 500 writes per batch
            i = 0;
            console.log('Intermediate committing of batch operation');
            await writeBatch.commit();
            writeBatch = firebaseAdmin.firestore().batch();
        }
        if (i > 0) {
            console.log('Firebase batch operation completed. Doing final committing of batch operation.');
            await writeBatch.commit();
        } else {
            console.log('Firebase batch operation completed.');
        }
    
    });

Inspired from @Lahiru Chandima's answer here, https://stackoverflow.com/a/60137639/3857918

PS: I have replaced your forEach with simple for..of loop here. The forEach async calls don't run in a sequence, can cause a lot of problems sometimes during debugging.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!