Firestore - Creating a Copy of a Collection

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

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.

Firebase Firestore clone documents subcolletions & data

There is no built-in operation to clone a document or collection. You will have to read the document/collection through the API and write the copy through that too.

Also see:

  • Cloud Functions: How to copy Firestore Collection to a new document?
  • Firestore - Recursively Copy a Document and all it's subcollections/documents (in Python, but with good code to start with)
  • Firestore - Creating a copy of a collection (in Swift)

How to copy a document in Firebase Firestore in same collection?

There is no copy operation. You will have to read the document, then write the document back with a new document ID.

It is possible to copy firebase document and all it sub collection to another document using angular

this is my solution but using callable cloud functions. You can play with source and dest params.

const functions = require( 'firebase-functions' );
const admin = require( 'firebase-admin' );

const copyDoc = async ( source, dest ) => {
const docRef = admin.firestore().doc( source );

const docData = await docRef
.get()
.then( ( doc ) => doc.exists && doc.data() )
.catch( ( error ) => {
console.error( 'Error reading document', `${source}`, error.message );
throw new functions.https.HttpsError( 'not-found', 'Copying document was not read' );
} );

if ( docData ) {
await admin
.firestore()
.doc( dest )
.set( docData )
.catch( ( error ) => {
console.error( 'Error creating document', `${dest}`, error.message );
throw new functions.https.HttpsError(
'data-loss',
'Data was not copied properly to the target collection, please try again.',
);
} );
}

const subcollections = await docRef.listCollections();
for await ( const subcollectionRef of subcollections ) {
const subPath = `${source}/${subcollectionRef.id}`
console.log( 'parsing: ', subPath )
try {
const snapshot = await subcollectionRef.get()
const docs = snapshot.docs;
for await ( const doc of docs ) {
console.log( `coping: ${subPath}/${doc.id} -> ${dest}/${subcollectionRef.id}/${doc.id}` )
await copyDoc( `${subPath}/${doc.id}`, `${dest}/${subcollectionRef.id}/${doc.id}` );
}
} catch ( e ) {
throw new functions.https.HttpsError(
'data-loss',
`${e.message} -> ${subPath}, please try again.`,
)
}
}
}

exports.set = functions
.region( 'europe-west3' )
.https.onCall( async ( {source_doc, destination_doc}, context ) => {
if ( !context.auth ) {
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError( 'unauthenticated', 'The function must be called while authenticated.' );
}
try {
await copyDoc( source_doc, destination_doc )
return { result: destination_doc }
} catch ( e ) {
throw new functions.https.HttpsError( 'aborted', e.message );
}
} );

Copy single document in Firestore and edit fields in new copy

Yo can do this by reading the collection, iterating on it and for each element of the collection 1 write it in collection 2.

Here is a quick example:

function copy(db){
db.collection('collection1').get()
.then((snapshot) => {
snapshot.forEach((doc) => {
// We are iterating on the documents of the collection
let data = doc.data();
console.log(doc.id, '=>', doc.data());
if(<PUT_CONDITIONS_HERE>){
//we have read the document till here
let setDoc = db.collection('collection2').doc(doc.id).set(data);
setDoc.then(res => {
console.log('Set: ', res);
});
}
});
})
.catch((err) => {
console.log('Error getting documents', err);
});
}

For more examples on how to read and write using the nodejs CLI you can go to the Github repository here

Also this can be done with a query from collection one to filter at that level, and iterate over less files. However this depends on the conditions you have to determine if it needs to be copied or not.

How to copy data between collections in firestore?

Looks like you are trying to access document data on the document snapshot, in this line:

'userName': doc['userName'],

Should be:

'userName': doc.data['userName'],

Final code, also with renamed var to reinforce it's a snapshot and not data:

void copyData() {
final databaseReference = Firestore.instance;
var docref = databaseReference.collection('verification').document("1604051013");
docref.get().then((docSnapshot) {
if (docSnapshot.exists) {
print("Document Data " + docSnapshot.data.toString());
databaseReference.collection("users").document("1").setData({
'userName': docSnapshot.data['userName'],
});
print(docSnapshot.data['userName']);
} else {
print("Error in firestore");
}
});
}

How to copy all documents from one collection to other in Firestore -Flutter?

Currently there's no way to copy a collection into another provided by firebase officially. And, for sure, you can iterate over your previous collection & create new documents in the other.

In your case you should be doing something like:

userFirebaseInstance
.collection(NewCollection)
.document()
.setData(YourDataHere)


Related Topics



Leave a reply



Submit