Skip to content

Latest commit

 

History

History
240 lines (162 loc) · 6.73 KB

5. Cloud Firestore.md

File metadata and controls

240 lines (162 loc) · 6.73 KB

Cloud Firestore

Cloud Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform. Like Firebase Realtime Database, it keeps your data in sync across client apps through realtime listeners and offers offline support for mobile and web so you can build responsive apps that work regardless of network latency or Internet connectivity.

Cloud Firestore's NoSQL data model, you store data in documents that contain fields mapping to values. These documents are stored in collections, which are containers for your documents that you can use to organize your data and build queries. Documents support many different data types, from simple strings and numbers, to complex, nested objects. You can also create subcollections within documents and build hierarchical data structures that scale as your database grows.

Create a Cloud Firestore project

  1. Open the Firebase Console and create a new project.

  2. In the Database section, click Try Firestore Beta.

  3. Click Enable.

Set up your development environment

Add the required dependencies and client libraries to your app.

  1. Follow the instructions to add Firebase to your Web app.
  2. Add the Firebase and Cloud Firestore libraries to your app:
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-app.js";
    import { getFirestore, collection, addDoc } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js";

Initialize Cloud Firestore

Initialize an instance of Cloud Firestore:

  firebase.initializeApp({
    apiKey: '### FIREBASE API KEY ###',
    authDomain: '### FIREBASE AUTH DOMAIN ###',
    projectId: '### CLOUD FIRESTORE PROJECT ID ###'
  });

Add Data

Cloud Firestore stores data in Documents, which are stored in Collections. Cloud Firestore creates collections and documents implicitly the first time you add data to the document. You do not need to explicitly create collections or documents.

Create a new collection and a document using the following example code.

import { getFirestore, collection, addDoc } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js";

// Your web app's Firebase configuration
const firebaseConfig = {
  //...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const db = getFirestore();

try {
    const ref = await addDoc(collection(db, 'users'), {name:'Vrijraj'})
    console.log(ref);
} catch (error) {
    console.log('error', e)
}

Set a document

When you use set() to create a document, you must specify an ID for the document to create. or To create or overwrite a single document, use the set() method using the following example code.

import { getFirestore, doc, setDoc } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js";

// Your web app's Firebase configuration
const firebaseConfig = {
  //...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const db = getFirestore();

await setDoc(doc(db, 'data', 'user1'), {name:'TechFerment'})

Read Data

Read Document Data which Document id: docid
    import { getFirestore, doc , getDoc } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js";

    // Your web app's Firebase configuration
    const firebaseConfig = { //... };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    
    const db = getFirestore();
    let docid = "YOUR_DOC_ID" 
    
    const docRef = doc(db, "data", docid);
    const docSnap = await getDoc(docRef);
    
    if (docSnap.exists()) {
      console.log("Document data:", docSnap.data());
    } else {
      // doc.data() will be undefined in this case
      console.log("No such document!");
    }
    
Read All the Documents
    import { getFirestore, collection, getDocs } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js";

    // Your web app's Firebase configuration
    const firebaseConfig = {
      //...
    };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    
    const db = getFirestore();

    const querySnapshot = await getDocs(collection(db, 'users'))
    let res = querySnapshot.docs.map(doc=> {
      return {...doc.data(),...{docid:doc.id}}
    })

    console.log(res);
Read Document Data in RealTime
    import { getFirestore, doc , onSnapshot } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js";

    // Your web app's Firebase configuration
    const firebaseConfig = { //... };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    
    const db = getFirestore();
    let docid = "YOUR_DOC_ID" 
    
    const unsub = onSnapshot(doc(db, "cities", docid), (doc) => {
        console.log("Current data: ", doc.data());
    });

Update Document

import { getFirestore, doc, updateDoc } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js";

// Your web app's Firebase configuration
const firebaseConfig = {
  //...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const db = getFirestore();

let docid = 'YOUR_DOC_ID'

const docRef = doc(db, 'data', docid)
        
// set name 'name1' to 'name2'
await updateDoc(docRef,{name:'name2'})

Delete Document

import { getFirestore, doc, deleteDoc } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js";

// Your web app's Firebase configuration
const firebaseConfig = {
  //...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const db = getFirestore();

let docid = 'YOUR_DOC_ID'
await deleteDoc(doc(db, "data", docid));
Delete fields

To delete specific fields from a document, use the FieldValue.delete() method when you update a document:

import { getFirestore, doc, updateDoc, deleteField } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js";

// Your web app's Firebase configuration
const firebaseConfig = {
  //...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const db = getFirestore();

let docid = 'YOUR_DOC_ID'

const docRef = doc(db, 'data', docid);

// Remove the 'capital' field from the document
await updateDoc(docRef, {
    capital: deleteField()
});

Data Modals

alt text

Backup with Extensions

npx @firebaseextensions/fs-bq-import-collection

// In BigQuery
// https://github.com/firebase/extensions/blob/master/firestore-bigquery-export/guides/IMPORT_EXISTING_DOCUMENTS.md
SELECT
  JSON_EXTRACT(DATA, '$.name') as name,
  JSON_EXTRACT(DATA, '$.age') as age
FROM `testtest-mappp.firestore_export.data_raw_latest`