DEV Community

codeHiccups
codeHiccups

Posted on

Firestore API : Getting started 🎁

Firestore API : Getting started

# STEP 1 :
const db = firebase.firestore()
Enter fullscreen mode Exit fullscreen mode
# STEP 2 :
  • 1. Connect to Collection
const collectionRef = db.collection("users");
Enter fullscreen mode Exit fullscreen mode

RETURNS collectionReference subset of queryReference

  • Not sure why but some how this is NOT an async opertation

NOTE : Now we will only talk about collectionReference object not documentRefernce

// collectionReference have few methods to get the snapshot

collectionRef.get();
Enter fullscreen mode Exit fullscreen mode

NOTE :

  1. All the above operations are async operations
  2. All the collectionReference operations RETURN querySnapshot

docs: An array that returns all of the documents in the snapshot

// querySnapshot has docs methods

collectionRef  //Reference from db.collection("users")
  .get()       // Get method to get query Snapshot
  .then((snapshot) => { // snapshot has docs property
    const data = snapshot.docs.map((doc) => ({ // which returns array
      id: doc.id,
      ...doc.data(), // of DocumentSnapshots, add data() to get JSON
    }));
Enter fullscreen mode Exit fullscreen mode
  • RECAP :
.data() | .exists
🔺
DocumentSnapshots
🔺
.docs()
🔺
querySnapshot
🔺
.get()
🔺
collectionReference
🔺
.collection()
Enter fullscreen mode Exit fullscreen mode

(OR)

  • 2. Connect to Document
const docRef = db.doc("/users/10")
Enter fullscreen mode Exit fullscreen mode

RETURNS documentReference subset of queryReference

  • Not sure why but some how this is NOT an async opertation

NOTE : Now we will only talk about documentRefernce object not collectionReference

// documentReference have few methods to get the snapshot

docRef.get();
docRef.set();
docRef.update();
docRef.delete();

Enter fullscreen mode Exit fullscreen mode

NOTE :

  1. All the above operations are async operations
  2. All the documentReference operations RETURN documentSnapshot
# DocumentSnapshot :

Document snapshot have two important methods

  1. .exists
  2. .data()
  • RECAP :
.data() | .exists
🔺
DocumentSnapshot
🔺
.get() | .set() | .update() | .delete()
🔺
documentRefernce
🔺
.docs()
Enter fullscreen mode Exit fullscreen mode

===============

Leverage Realtime

  • Instead of promise, it's a subscription

use .onSnapshot(cb) on collection reference

  • Whenever data changes, firestore calls the callback with querySnapshot
(snapshot) => {
    const data = snapshot.docs.map((doc) => ({
      id: doc.id,
      ...doc.data(),
    })
Enter fullscreen mode Exit fullscreen mode

Top comments (0)