Home > Software design >  How to query Firebase with Node.js and "firebase-admin" SDK?
How to query Firebase with Node.js and "firebase-admin" SDK?

Time:08-17

After initializing Firebase like this:

import * as admin from "firebase-admin"
const firebaseApp = admin.initializeApp({
    credential: admin.credential.cert(keys),
})
export const db = firebaseApp.firestore()

I want to get all documents of one collection ("players"). I use this:

 const ref = db.collection('players');
 const allPlayers = await ref.get();

And I get this object as a result:


QuerySnapshot {
[1]   _query: CollectionReference {
[1]     _firestore: Firestore {
[1]       _settings: [Object],
[1]       _settingsFrozen: true,
[1]       _serializer: [Serializer],
[1]       _projectId: 'grampsio-ds-verify',
[1]       registeredListenersCount: 0,
[1]       bulkWritersCount: 0,
[1]       _backoffSettings: [Object],
[1]       _clientPool: [ClientPool]
[1]     },
[1]     _queryOptions: QueryOptions {
[1]       parentPath: [ResourcePath],
[1]       collectionId: 'players',
[1]       converter: [Object],
[1]       allDescendants: false,
[1]       fieldFilters: [],
[1]       fieldOrders: [],
[1]       startAt: undefined,
[1]       endAt: undefined,
[1]       limit: undefined,
[1]       limitType: undefined,
[1]       offset: undefined,
[1]       projection: undefined,
[1]       kindless: false,
[1]       requireConsistency: true
[1]     },
[1]     _serializer: Serializer {
[1]       createReference: [Function (anonymous)],
[1]       createInteger: [Function (anonymous)],
[1]       allowUndefined: false
[1]     },
[1]     _allowUndefined: false
[1]   },
[1]   _readTime: Timestamp { _seconds: 1660695591, _nanoseconds: 108996000 },
[1]   _size: 1,
[1]   _materializedDocs: null,
[1]   _materializedChanges: null,
[1]   _docs: [Function (anonymous)],
[1]   _changes: [Function (anonymous)]
[1] }

How do I get the two expected documents out of it or has the query already failed?

CodePudding user response:

My guess is that you did console.log(allPlayers), which shows are the internals of a QuerySnapshot object.

To get the documents in there, check its docs property. For example:

allPlayers.docs.forEach((docSnapshot) => {
  console.log(docSnapshot.id, docSnapshot.data());
})

Note that this is pretty close to the example in the Firebase documentation on getting all documents from a collection, so I recommend keeping that handy while developing.

  • Related