Get All Dictionary Keys in Firestore Using Firebase Cloud Functions


firebaseIn Firebase, you can get all the keys of an Object very easily. The thing that you should note is that a dictionary is just an Object in Firestore.

All the custom Objects that you store in the Firestore behave just like the native Javascript objects.
To get all keys of an object, you can simply use the Object.keys() method that is available for all the Objects in Javascript.

But, of course, you first have to get the Object from Firestore to read it locally. In fact, all the operations in Objects (and by extension, Arrays) can only be done locally in order to modify them.

This simply means that in order to mutate an Object, you first have to read it from the Cloud Firestore DB. Perform your update/delete operation and then overwrite that value to the DB.

Fetching an Object from Firestore

Let’s suppose that you have the following object in your Firestore Database.

schedule: {
  startTime: "Wed May 23 2018 18:00:00 GMT+0530",
  endTime: "Wed May 23 2018 20:00:00 GMT+0530"

This object has two keys in it. The startTime and the endTime.

In Cloud Functions, you can get all the keys of this Object by using the Admin SDK. Here’s how the code will look like:

const functions = require('firebase-functions');
/** admin SDK is required for reading from the Firestore */
const admin = require('firebase-admin');


const db = admin.firestore();

 * Returns the keys of an object on request.
 * @param {Object} req Express `request` object.
 * @param {Object} res Express `response` object.
const getKeys = (req, res) => {
  const docRef = db.doc('doc/path');

  docRef.get().then((doc) => {
    const keys = Object.keys(doc.get('schedule'));
    /** res.end() sends the string response to the requester */

module.exports = {
  /** function will be available at `/api` to you */
  api: functions.https.onRequest(getKeys),

The output of Cloud Function

// output
["startTime", "endTime"]

You can see, this works the same way as it does for plain JS Objects.

You’ll obviously need to customize this code based on your requirement, but the gist of will remain the same.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.