Get All Dictionary Keys in Firestore Using Firebase Cloud Functions

In 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.

1
2
3
4
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const functions = require('firebase-functions');
/** admin SDK is required for reading from the Firestore */
const admin = require('firebase-admin');

admin.initalizeApp();

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 */
res.end(JSON.stringify(keys));
});
};

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

Output of the Cloud Function

1
2
// 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.