1

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));
  });
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Jerry Seigle
  • 417
  • 4
  • 12

1 Answers1

2

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.

Utkarsh Dixit
  • 4,267
  • 3
  • 15
  • 38
  • This works but I had to move the await writeBatch.commit(); outside of the for loop. Question is there a way to add and element to the data before the copy is sent to the other collection – Jerry Seigle Aug 23 '21 at 14:45