0

I have this function which accepts a DataSnapshot as an argument. My current work around was, I still have to know beforehand, what keys I have on my firestore document.

This is really not efficient enough, I would like to figure out a way to actually retrieve all fields that are reference data types without knowing the keys beforehand. That would make this Promise more useful, for instance you can just pass in any DataSnapshot and it will resolve into a document with the referenced documents appended.

getDenormalizedFields = (data: Object): Promise<any> => {
    const denormalizeKeys = ['refOne', 'refTwo', 'refThree'];
    const denormalizationPromise = new Promise(async (resolve: Function) => {
      const denormalizations = await denormalizeKeys.map(
        async (key: string) => {
          const field = await data[key].get();
          const fieldData = await field.data();

          return { [key]: fieldData };
        },
      );
      const promisedDenormalizations = await Promise.all(denormalizations);
      const denormalized = Object.assign({}, ...promisedDenormalizations);

      resolve(denormalized);
    });

    return denormalizationPromise;
  };
Jojo Narte
  • 2,767
  • 2
  • 30
  • 52

1 Answers1

0

The data() method on DocumentSnapshot gives you a raw JavaScript object with the contents of the document. You can iterate the keys of this object in the normal way you would for any JavaScript object, then check the value for each key. You can find out if the value is a DocumentReference by checking its type, then take whatever action you want with it.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • when I `console.log` type of of each data via Object.keys(data).forEach(key => console.log(typeof data[key])); `DocumentReference` are of type object, isn't there a way to distinguish which is the exact `DocumentReference` in JS? – Jojo Narte Jul 13 '18 at 01:54
  • Check to see if it has the methods you'd like to call. Or use TypeScript, which makes everything easier. – Doug Stevenson Jul 13 '18 at 04:53