Skip to content

Latest commit

 

History

History
197 lines (171 loc) · 6.75 KB

File metadata and controls

197 lines (171 loc) · 6.75 KB

2. Documents in AngularFirestore

Cloud Firestore is a NoSQL, document-oriented database. Unlike a SQL database, there are no tables or rows. Instead, you store data in documents, which are organized into collections. Each document contains a set of key-value pairs. Cloud Firestore is optimized for storing large collections of small documents.

This documentation is updated for modular version 9 of angular fire package. For previous or missing features refer to older docs.

Features list of document querying

  1. Create a document
  2. Update a document
  3. Delete a document
  4. Observer a document for changes
  5. Inline querying like
  • Incrementing field value
  • Adding a data in an array
  • Removing a data from an array
  1. Offline data persistence

Create a document

Create the document in a fixed document id

import { Component, OnInit } from '@angular/core';
import { Firestore } from '@angular/fire/firestore';
import { doc, getDoc } from 'firebase/firestore';

@Component({
  selector: "app-root",
  template: `
    <ul>
      <li *ngIf="data">
        {{ data.name }}
      </li>
    </ul>
  `,
})
export class AppComponent implements OnInit {
  data: any = {};
  constructor(private firestore: Firestore) {}
  ngOnInit() {
    getDoc(doc(this.firestore,'data/Pn5oHxAjpnSEAPJABj22')).then((data)=>{
      this.data = data.data();
    })
  }
}

Add the document inside a collection

Here the document with data {name:'Rick Roll'} will be added to collection data with unique random id generated by firebase firestore

import { Component, OnInit } from '@angular/core';
import { Firestore } from '@angular/fire/firestore';
import { doc, addDoc } from 'firebase/firestore';

@Component({
  selector: "app-root",
  template: `<p>Check console</p>`,
})
export class AppComponent implements OnInit {
  constructor(private firestore: Firestore) {}
  ngOnInit() {
    addDoc(collection(this.firestore,'data'),{name:'Rick Roll'}).then((data)=>{
      console.log('Doc added');
    })
  }
}

Update doc with new data

This method changes the data inside the document mydoc which is inside the collection data with he new data {name:'Updated name is rick roll'}

import { Component, OnInit } from '@angular/core';
import { Firestore } from '@angular/fire/firestore';
import { doc, updateDoc } from 'firebase/firestore';

@Component({
  selector: "app-root",
  template: `<p>Check console</p>`,
})
export class AppComponent implements OnInit {
  constructor(private firestore: Firestore) {}
  ngOnInit() {
    updateDoc(doc(this.firestore,'data/mydoc'),{name:'Updated name is rick roll'}).then((data)=>{
      console.log('Doc updated');
    })
  }
}

Delete a doc

This method deletes the document mydoc which is inside the collection.

import { Component, OnInit } from '@angular/core';
import { Firestore } from '@angular/fire/firestore';
import { doc, deleteDoc } from 'firebase/firestore';

@Component({
  selector: "app-root",
  template: `<p>Check console</p>`,
})
export class AppComponent implements OnInit {
  constructor(private firestore: Firestore) {}
  ngOnInit() {
    deleteDoc(doc(this.firestore,'data/mydoc')).then((data)=>{
      console.log('Doc deleted');
    })
  }
}

Get realtime updates on document data

This methods returns you a subscription from which you can subscribe and get the latest data whenever the document changes it's data.

import { Component, OnInit } from '@angular/core';
import { Firestore } from '@angular/fire/firestore';
import { doc, docData } from 'firebase/firestore';
import { Subscription } from 'rxjs';

@Component({
  selector: "app-root",
  template: `
    <h1>This data will change when data inside document changes </h1>
    <p>Data {{this.documentData}}</p>`,
})
export class AppComponent implements OnInit, OnDestroy {
  constructor(private firestore: Firestore) {}
  documentSubscription:Subscription = Subscription.EMPTY;
  documentData:any = {}
  ngOnInit() {
    this.documentSubscription = docData(doc(this.firestore, 'data/Pn5oHxAjpnSEAPJABj22')).subscribe(
      (data: any) => {
        this.documentData = data.data()
        console.log('Doc changed',data.data())
      }
    );
  }
}

Inline Querying and data manipulation

Incrementing field value

import { Component, OnInit } from '@angular/core';
import { Firestore } from '@angular/fire/firestore';
import { doc, docData } from 'firebase/firestore';
import { Subscription } from 'rxjs';

@Component({
  selector: "app-root",
  template: `<h1>Everytime you refresh the page your score increases by 4</h1>`,
})
export class AppComponent implements OnInit, OnDestroy {
  constructor(private firestore: Firestore) {}
  ngOnInit() {
    updateDoc(doc(this.firestore, 'data/Pn5oHxAjpnSEAPJABj22'), {score:increment(4)}).then(()=>{
      console.log('incremented');
    })
  }
}

Other field value functions are also accepted like

  1. increment(n) Increments the specified value by n
  2. arrayRemove(n) Removes the data n from a specified array
  3. arrayUnion(n) Adds the data n to specified array

##Access data offline

Cloud Firestore supports offline data persistence. This feature caches a copy of the Cloud Firestore data that your app is actively using, so your app can access the data when the device is offline. You can write, read, listen to, and query the cached data. When the device comes back online, Cloud Firestore synchronizes any local changes made by your app to the Cloud Firestore backend.

To use offline persistence, you don't need to make any changes to the code that you use to access Cloud Firestore data. With offline persistence enabled, the Cloud Firestore client library automatically manages online and offline data access and synchronizes local data when the device is back online.

Configure offline persistence

When you initialize Cloud Firestore, you can enable or disable offline persistence:

  • For Android and Apple platforms, offline persistence is enabled by default. To disable persistence, set the PersistenceEnabled option to false.
  • For the web, offline persistence is disabled by default. To enable persistence, call the enablePersistence method. Cloud Firestore's cache isn't automatically cleared between sessions. Consequently, if your web app

For more info refer here

This will enable persistence in your firestore database In your app.module.ts file add this when initializing firestore

import { enableIndexedDbPersistence } from 'firebase/firestore';
import { provideFirestore,getFirestore } from '@angular/fire/firestore';

@NgModule({
  imports:[
    provideFirestore(()=>{
      const firestore = getFirestore();
      enableIndexedDbPersistence(firestore);
      return firestore
    }),
  ]
})