In my firestore database I have the following db schema populated with documents
root
|
|---transactions/...
I want to move all transactions to a new subcollection like:
root
|
|---users/user/transactions/...
How do I accomplish this?
After trying a few approaches (see further below) here is what worked for me:
1. Migrate data with custom function using the @angular/fire SDK:
// firebase.service.ts
import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { first, map } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class FirebaseService {
fromCollection = '<name-of-collection>';
toCollection = '<other-root-level-collection>/<document-id>/<subcollection>';
constructor(private firestore: AngularFirestore) {}
migrateTransactions() {
this.getAllDocuments<YourType>(this.fromCollection).subscribe((documents) => {
documents.forEach(async (document) => {
await this.createDocument(this.toCollection, document);
});
});
}
getAllDocuments<T>(path: string) {
return this.firestore
.collection(path)
.get()
.pipe(
first(),
map((collection) => collection.docs.map((doc) => doc.data() as T))
);
}
createDocument(path: string, document: unknown) {
return this.firestore.collection(path).add(document);
}
}
Note: This only ADDS all documents from the origin to the targeted collection - it does NOT delete the original documents or overwrite any existing documents, so it is very safe to use. Afterwards you can delete the origin collection in the Firebase console.
Remember, that you can concatenate nested collections and documents and pass it as argument to AngularFirestore.collection(path) (as seen in property toCollection). This makes it easy to traverse nested collections. Whether this is possible in other SDKs I don't know.
2. Migrate using firestore-migrator by Jeff Delaney:
This didn't work for me as the library failed at converting firebase's timestamps. If you don't have any complex data types in your schema, it will probably work. The library itself is a great utility and can be made to work locally if you are willing to tinker a bit.
3. Migrate using the Cloud Firestore managed export and import service:
This only works for complete backups of either the whole database or a root level collection. So this might not be what you are looking for.