Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Functions: How to copy Firestore Collection to a new document?

Tags:

I'd like to make a copy of a collection in Firestore upon an event using Cloud Functions

I already have this code that iterates over the collection and copies each document

const firestore = admin.firestore() firestore.collection("products").get().then(query => {   query.forEach(function(doc) {     var promise = firestore.collection(uid).doc(doc.data().barcode).set(doc.data());   }); }); 

is there a shorter version? to just copy the whole collection at once?

like image 768
Khaled Avatar asked Apr 06 '18 10:04

Khaled


People also ask

How do I get data from firestore to Doc?

There are three ways to retrieve data stored in Cloud Firestore. Any of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data once. Set a listener to receive data-change events.


2 Answers

I wrote a small nodejs snippet for this.

const firebaseAdmin = require('firebase-admin'); const serviceAccount = '../../firebase-service-account-key.json'; const firebaseUrl = 'https://my-app.firebaseio.com';  firebaseAdmin.initializeApp({     credential: firebaseAdmin.credential.cert(require(serviceAccount)),     databaseURL: firebaseUrl }); const firestore = firebaseAdmin.firestore();  async function copyCollection(srcCollectionName, destCollectionName) {     const documents = await firestore.collection(srcCollectionName).get();     let writeBatch = firebaseAdmin.firestore().batch();     const destCollection = firestore.collection(destCollectionName);     let i = 0;     for (const doc of documents.docs) {         writeBatch.set(destCollection.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.');     } }  copyCollection('customers', 'customers_backup').then(() => console.log('copy complete')).catch(error => console.log('copy failed. ' + error)); 
like image 84
Lahiru Chandima Avatar answered Oct 30 '22 13:10

Lahiru Chandima


Currently, no. Looping through each document using Cloud Functions and then setting a new document to a different collection with the specified data is the only way to do this. Perhaps this would make a good feature request.

How many documents are we talking about? For something like 10,000 it should only take a few minutes, tops.

like image 26
rayfarer Avatar answered Oct 30 '22 13:10

rayfarer