jennie788
jennie788

Reputation: 456

How do I add Firestore to my Javascript code?

In Javascript, I've been trying to add Firestore using the code below:

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-analytics.js";
import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-firestore.js";

const firebaseConfig = {
    apiKey: "XXXXX",
    authDomain: "XXXXX",
    projectId: "XXXXX",
    storageBucket: "XXXXX",
    messagingSenderId: "XXXXX",
    appId: "XXXXX",
    measurementId: "XXXXX"
};

const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const db =  getFirestore();   

db.collection("users").where("uid", "==", "1234")
.onSnapshot((snapshot) => {
    snapshot.docChanges().forEach((change) => {
        console.log("change ", change.doc.data());
    });
});

However, I get the following error:

Uncaught TypeError: db.collection is not a function

Please help, thanks.

Upvotes: 0

Views: 58

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50850

You are using modular version so try refactoring the onSnapshot to this syntax:

import { collection, query, where, onSnapshot } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-firestore.js";

const q = query(collection(db, "users"), where("uid", "==", "1234"));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
  const documents = [];
  querySnapshot.forEach((doc) => {
      documents.push(doc.data().name);
  });
});

Upvotes: 1

Related Questions