Home > Mobile >  Firestore - Clever approach to converting all Firestore.Timestamp objects into Javascript date
Firestore - Clever approach to converting all Firestore.Timestamp objects into Javascript date

Time:02-02

I have a collection of objects that I want to retrieve. The objects have some date key:value pairs in them and I want to return all of those as a proper Javascript date. I don't want to declare them all one-by-one, as there are some dates that only exist on some objects, some I might not know about and in general, it's frustrating to declare everything one-by-one.

Here is my code that does not work, how could I get it working?

async function getChargesFromDatabase() {
  const chargesCol = fsExpenses.collection('charges');
  const chargesDocs = (await chargesCol.limit(50).orderBy('startTs', 'desc').get()).docs.map((doc) => {
    const returnDoc: any = {};
    for (const [key, value] of Object.entries(Object.entries(doc.data()))) {
      returnDoc[key] = value?.toDate() ?? value;
    }
    return returnDoc;
  });
  return chargesDocs;
}

CodePudding user response:

You will have to check all the keys as you are doing now by checking if a field is instance of Firestore Timestamp. Try using the following function:

const convertTimestamps = (obj: any) => {
  if (obj instanceof firebase.firestore.Timestamp) {
    return obj.toDate();
  } else if (obj instanceof Object) {
    // Check for arrays if needed
    Object.keys(obj).forEach((key) => {
      obj[key] = convertTimestamps(obj[key]);
    });
  }
  return obj;
};
async function getChargesFromDatabase() {
  const chargesCol = fsExpenses.collection('charges');
  const chargesSnap = await chargesCol.limit(50).orderBy('startTs', 'desc').get()
  const chargesDocs = chargesSnap.docs.map((doc) => convertTimestamps(doc.data()))
}
  • Related