0

I am trying to connect to firebase realtime database (not firestore) but I get the error that db.collection is not a function. Other answers in StackOverflow are mentioned with respect to Firestore. Thanks for your help.

const admin = require('firebase-admin');

// Firebase configuration - this should not be public.
// Please use your own config if you intend to use this code.
var firebaseConfig = {
  apiKey: "xxxxxxxxxxxxxxxxxx",
  authDomain: "xxxxxxxxxxxxxxxxxx",
  databaseURL: "xxxxxxxxxxxxxxxxxx",
  projectId: "xxxxxxxxxxxxxxxxxx",
  storageBucket: "xxxxxxxxxxxxxxxxxx",
  messagingSenderId: "xxxxxxxxxxxxxxxxxx",
}

// Initialize Firebase
admin.initializeApp(firebaseConfig)

const db = admin.database();
console.log("Database setup");

(async () => {
  try {
    let query = db.collection('users');
    console.log("Doing database query now");
    await query.get().then(querySnapshot => {
      console.log(querySnapshot);
    });
  } catch (error) {
    console.log(error);
  }
})();
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Mayuresh Anand
  • 193
  • 1
  • 3
  • 10

1 Answers1

2

const db = admin.database() is an instance of Firebase realtime database and not Firestore. To get an instance of Firestore, use admin.firestore().

const admin = require('firebase-admin');

admin.initializeApp(/* service account */)

const db = admin.firestore();
console.log("Firestore setup");

Admin SDK uses a service account and not the same public credentials. You can refer to the documentation for detailed information. You can get a service account from project settings.

Do note that if you are using Cloud functions then you can leave initializeApp() empty.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • I am working with the real-time database.. can you please give me suggestion regarding how can I connect to realtime database and retrieve data from it. Thanks – Mayuresh Anand Aug 28 '21 at 12:12
  • 1
    @MayureshAnand you can refer to to the [documentation](https://firebase.google.com/docs/database/admin/retrieve-data#node.js). It has plenty of examples. `admin.database().ref("/path").once("value")` – Dharmaraj Aug 28 '21 at 12:17
  • 1
    The the Node.js Admin SDK, also see this [getting started guide](https://firebase.google.com/docs/database/admin/start#node.js). – Frank van Puffelen Aug 28 '21 at 14:26
  • This help me! at first I have confusing error using db = getFirestore(app), changing it to admin.firestore() solved it. Why though? – swdev Apr 07 '23 at 14:50