What is the process for transferring an existing collection or data in Firestore to a subcollection?

My firestore database currently has the following structure with documents:

root
|
|---transactions/...

I am looking to transfer all transactions to a new subcollection as shown below:

root
|
|---users/user/transactions/...

Any suggestions on how I can achieve this?

Answer №1

After experimenting with different methods (outlined below), I found a solution that worked for me:

1. Transfer data using a custom function utilizing 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 method only ADDS all documents from the original collection to the specified collection - it does NOT delete the original documents or overwrite existing ones, ensuring safety. You can subsequently remove the original collection in the Firebase console.

Keep in mind you can concatenate nested collections and documents when passing them as arguments to

AngularFirestore.collection(path)
(as demonstrated in the property toCollection). This simplifies navigation through nested collections. Other SDKs may not support this feature.

2. Utilize firestore-migrator by Jeff Delaney:

This approach did not work for me due to issues with converting firebase's timestamps. However, if your schema does not contain complex data types, it might be suitable. The library itself is useful and can be adjusted locally with some tinkering.

3. Use the Cloud Firestore managed export and import service:

This is ideal for complete backups of either the entire database or a root level collection. It may not meet every requirement, so evaluate if it aligns with your needs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can two writable stores in Svelte be set up to subscribe to each other simultaneously?

There is a unique scenario where two objects share data, yet have different structures. For instance, the 'Team' object has the team ID as its key. The 'Team' object includes 'name' and 'users' objects as its values ...

Encountering Problem with Jmeter Script Playback - Kindly Activate JavaScript to Access Page Information

I'm currently experiencing a challenge when trying to simulate the following scenario in my JMeter script. I would truly appreciate any assistance or solutions you can offer. My goal is to create a JMeter script for a form submission process within a ...

What are the best practices for running node in VSCode?

$ node test.js internal/modules/cjs/loader.js:883 throw err; ^ I have exhausted all possible solutions, including checking the PATH route for Node.js, restarting, and using different files. Despite the fact that I am able to retrieve the version when ...

Identifying modifications within the @Input property in Angular 4

Can someone clarify how to detect changes in an @Input property within a component, rather than just when passed from its parent? I haven't found a clear answer to this yet. Thank you! ...

What is the process for uploading a single file and an array of files with varying names using multer?

I am having trouble figuring out how to upload a main image and side images from 2 different file inputs using multer. It seems that multer only accepts one upload per route. How can I work around this issue? I keep getting an unexpected field error when a ...

Transmitting multiple parameters, including a file, from Angular to Spring framework

I am attempting to send an http request with multiple parameters to Spring. One of the parameters is a file, but I keep receiving a bad request error from the server. I am confident that I have made a mistake somewhere, and I would appreciate your assistan ...

Implementing Axios interceptor is a common practice in Vue.js applications to central

Hello everyone, I'm facing a problem with the interceptor in VueJS. I can't seem to figure out where the issue lies and it's driving me crazy... I've gone through various tutorials and read numerous posts on stackoverflow, but everythi ...

What is the best approach for developing an npm package containing multiple Vue directives? Should each directive have its own separate package, or should they

While I have successfully created an npm package by exporting a single vue directive in the src/index.js file, I am now faced with the challenge of creating a package that allows for the use of multiple vue directives. Unfortunately, I have been unable t ...

Two separate menus for each root file in Ionic 2

In my Ionic 2 project, I have developed two root files: app.component and report-menu. In order to make the report-menu module accessible in the app.component.module.ts file, I imported it successfully. However, I am facing an issue where one menu is dis ...

Receiving an error stating "module not found" when attempting to retrieve the NextAuth session using EmailProvider in getServerSideProps

Trying to access the NextAuth session from a server-side call within getServerSideProps, using an EmailProvider with NextAuth. Referring to an example in NextAuth's documentation, I'm attempting to retrieve the session from getServerSideProps. T ...

"Trying to refresh your chart.js chart with updated data?”

Greetings! I have implemented a chart using chart.js and here is the corresponding code: let myChart = document.getElementById('myChart').getContext('2d'); let newChart = new Chart(myChart, { type: 'line', data: { labels: ...

Having trouble getting Vue.js hello world to display on the page

I am attempting to create a Hello World app following the Vue.js site's get started documentation. Everything seems to be in order, but only the HTML code is being displayed on the page. Vue version: 1.0.26 Below is the HTML code: <!DOCTYPE ht ...

Is there a way to dynamically change the helperText of a Material UI TextField using its current value through code?

I'm currently attempting to dynamically change the helperText of a Material UI TextField based on the value entered into the field. Below is my current implementation: const defaultScores = { STR: 10, DEX: 10, CON: 10, INT: 10, WIS: 10, CH ...

Troubleshooting the integration of Text Mask Library with Vue - issue: no export named 'default' available

I was able to implement the vanilla JavaScript version: var maskedInputController = vanillaTextMask.maskInput({ inputElement: document.querySelector('.myInput'), mask: [/\d/, /\d/, '/', /\d/, /\d/, '/ ...

Unable to send POST request (including data) using event trigger from an external component

I'm currently facing an issue where a click event in one component is triggering a method in another, but the data that should be passed in my POST request isn't being sent. Interestingly, when I test the functionality by calling the method dire ...

Exploring the significance of a super in Object-Oriented Programming within JavaScript

During my studies of OOP in JS, I encountered the super() method which serves to call the constructor of the parent class. It made me ponder - why is it necessary to invoke the parent class constructor? What significance does it hold for us? ...

Looking for a way to locate any elements in jQuery that do not contain a certain CSS class?

I am looking to target all form elements that do not contain a specific CSS class. For example: <form> <div> <input type="text" class="good"/> <input type="text" class="good"/> <input type="text" class="bad"/> ...

"Encountering difficulties while setting up an Angular project

I am currently working on setting up an Angular project from scratch. Here are the steps I have taken so far: First, I installed Node.js Then, I proceeded to install Angular CLI using the command: npm install -g @angular/cli@latest The versions of the ...

Displaying Material UI Styles: A Challenge

Currently working on a website using Material-UI and React. Strangely, the styling applied through Material-UI's Hook API functions perfectly on codesandbox.io but fails to work when running locally. Notably, the border radius feature fails to update ...

Enhance the <div> with interactive content through dynamic updates on click within the same element

I am currently developing an Editor-Menu for a website administration. When I open admin.php, the Editor-Menu should be loaded into the #ausgabe div using the code $('#ausgabe').load('./admin-ajax/ajax2.php'). This functionality is work ...