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

Tips for fixing the async/await problem in JavaScript

Here is the code I've been working on: let icsFileData = []; icsFileData = filterAttachmentArray.map(async(file) => { let buff = new Buffer(file.data, 'base64'); let text = buff.toString('ascii'); const data = await ical ...

Where is the destination of the response in a Client-Side API Call?

I have developed an API that accepts a person's name and provides information about them in return. To simplify the usage of my API for third parties on their websites, I have decided to create a JavaScript widget that can be embedded using a script ...

What is the best way to create a navigation bar that opens on the same page when clicked?

Can someone help me figure out how to create a navbar that, when clicked, opens a small window on the same page like in this example image? ...

What steps should be taken to address the Chrome alert stating that the deferred DOM Node cannot be identified as a valid node?

While working on my node.js project hosted on a localhost server, I've encountered an unusual warning message in the inspector. The warning states: The deferred DOM Node could not be resolved to a valid node. Typically, I use the inspector to examine ...

new cookies are created without human intervention

Working on a project in Next.js and using the react-cookie npm package for managing sessions. I am creating a cookie with the key name "token" and assigning the token value as its value. However, an issue has arisen related to cookies where multiple cooki ...

What can cause a problem with the reduce function that populates an empty object with keys in TypeScript?

I've encountered an issue with a function that is meant to reduce an object. The problem lies in using the reduce method to assign the values of acc[key] as object[key], which is resulting in errors in the code. I am trying to avoid using any specific ...

What is the best way to apply styling exclusively to a child component?

I am currently working on a coding project that involves a parent component and multiple child components. My main goal is to adjust the position of a filter icon by moving it down 5 pixels on one specific child component. The issue I am facing is that no ...

Updating Google+ url parameter dynamically without the need to reload the page

Is there a way for a user to share a link on social media platforms like Facebook and Google+ without having to refresh the page? The user can customize the link with an ajax call, ensuring that the page remains static. Here is my code for the Google Plu ...

Validating optional fields in React

My registration form includes the following fields: Name Email Password Confirm password Optional field Select role (student, professor, secretary) Here's what I'm trying to achieve: If I want to create a user with a student role, the optional ...

Fix for sorting issue in Angular 4.4.x mat-table header

I am facing an issue with my mat-table sorting header. I have followed the examples and decorated the columns accordingly: <ng-container matColumnDef="id"> <mat-header-cell *matHeaderCellDef mat-sort-header> Id </mat-header-cell> & ...

What are some javascript libraries that can be used to develop a mobile image gallery for both Android and iPhone

I currently have the touch gallery system in place, but unfortunately it isn't functioning properly on Android devices. ...

Spin a child element by clicking on its parent component

I am looking to create a unique animated effect for the arrows on a button, where they rotate 180 degrees each time the button is clicked. The concept involves rotating both sides of the arrow (which are constructed using div elements) every time the con ...

Executing a JavaScript function within Python using Selenium: A beginner's guide

Within my JavaScript, there is a function called 'checkdata(code)' which requires an argument named 'code' to execute and returns a 15-character string. I recently discovered how to call functions without arguments in JavaScript. Howev ...

The first time I try to load(), it only works partially

My script used to function properly, but it has suddenly stopped working. Can anyone help me figure out why? The expected behavior is for the referenced link to be inserted into target 1, while target 2 should be updated with new content from two addition ...

Managing POST request data in Express: A step-by-step guide

Currently, I am facing an issue with my alert button on the client side, which has an event listener that is supposed to send data to the server. Below is the code snippet for the client side: alertBtn.addEventListener("click", () => { axios ...

A guide to creating a synchronous AJAX call using vanilla JavaScript

I am trying to make multiple AJAX calls in a loop using the code below. for (var i = 0; i < 5; i++) { console.log(i); ajax_DatabaseAccessor.query("CheckInt", i, loadQuery); function loadQuery(data) { alert(DWRUtil.toDescriptiveString ...

Angular 9: The instantiation of cyclic dependencies is not allowed

After transitioning from Angular 8 to Angular 9, I encountered an issue with a previously functioning HTTP communication service. The error message now reads: Error: Cannot instantiate cyclic dependency! HttpService at throwCyclicDependencyError (core ...

What causes the consistency in output when various encodings are applied in Node.js with fs.readFileSync()?

I've been puzzled by why using the readFileSync method with different encodings (such as utf-8, hex, ascii) always gives me the same output on the console. It's also strange that when I don't specify any encoding, I still get the output in u ...

What is the best way to access JSON data that is saved in a variable located within a separate component?

I'm currently utilizing axios to fetch JSON data from my API, mapping it, and storing it as a variable. I'm struggling to figure out the optimal way to call these variables within my React components. Retrieving and Storing JSON Data as Variable ...

Guide on incorporating Kendo UI typings into a TypeScript module

Currently, I am working with Kendo UI for React and TypeScript. My goal is to import the Kendo UI typings for TypeScript using a "typeof import". Following the guidance provided at https://docs.telerik.com/kendo-ui/third-party/typescript, I successfully i ...