Skip to content

Instantly share code, notes, and snippets.

@debojyoti
Last active March 11, 2019 05:34
Show Gist options
  • Save debojyoti/adead1c775c155b2e4df8bdb8f3c6c36 to your computer and use it in GitHub Desktop.
Save debojyoti/adead1c775c155b2e4df8bdb8f3c6c36 to your computer and use it in GitHub Desktop.
A to Z of firestore operations in an angular app

Firebase crud operations in angular

Initial setup

npm install firebase @angular/fire --save

Register in app module

...
import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';

const config = {
  apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
  authDomain: "xxxxxxxxxxxxxxxxxxxxxxxx",
  databaseURL: "xxxxxxxxxxxxxxxxxxxxxxxxxx",
  storageBucket: "xxxxxxxxxxxxxxxxxxxxx",
  messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxxxxxx"
};

@NgModule({
  imports:      [ 
    ...
    AngularFireModule.initializeApp(config),
    AngularFirestoreModule
  ],
  declarations: [ ... ],
  bootstrap:    [ ... ]
})
export class AppModule { }

Inject firebaseapp in the required component

...
import { AngularFirestore } from '@angular/fire/firestore';
...
export class AppComponent  {
  constructor(public db: AngularFirestore) {
  }
}

Opertaions to set/update data (create)

  1. Add a new doc (auto generated id)
this.db.collection("cities").add({
    name: "Tokyo",
    country: "Japan"
})
.then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
    console.error("Error adding document: ", error);
});
  1. Add a new doc (with custom id)
var docData = {
    stringExample: "Hello world!",
    booleanExample: true,
    numberExample: 3.14159265
};

this.db.collection("data").doc("one").set(docData).then(function() { // <<<< "one" is the custom id
    console.log("Document successfully written!");
});

If a doc already exists with same id, it will overwrite the contents While adding new doc if the collection doesn't exist, it will create the collection also So to create a collection, atleast one doc is required

Opertaions to read data

There are basically two ways to read data

  1. Call a method to get the data
  2. Set a listener to receive data-change events

1.1 Call a method to get a specific doc data

let docRef = this.db.collection("cities").doc("SF");

docRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});

1.2 To get all doc from a specific collection

this.db.collection("cities").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
    });
});

1.3 Get multiple documents from a collection based on some filter

this.db.collection("cities").where("capital", "==", true)
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data());
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });

2.1 Get the value instantly and also listen for updates

this.db.collection("cities").where("capital", "==", true)
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data());
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment