'Importing dates/timestamps into Firebase Cloud Firestore using a json file

I’m new to Firebase and noSQL databases. I expected to find a wizard that would take a simple Excel .csv file and import into Firebase but no luck.

I want to import a few simple records How to upload data worked well but can I modify it to import dates? I’m assuming Firestore converts date or date/time to a timestamp and stores it internally as a number.

This walkdate gets imported as a string.

[{
    "walkid": "555",
    "walkdate": "2019-11-19T13:59:00",
    "briefdescription": "ESSEX "
}
]


Solution 1:[1]

There's a great tutorial that shows how to get started with Firestore using a CSV.

https://medium.com/@impaachu/how-to-upload-data-to-firebase-firestore-cloud-database-63543d7b34c5

It makes sense to go through the set up as you'll need to use a similar one to use Firestore in practice. Once you've set it up once (the first part of the tutorial involving initializeApp), you'll be in a pretty good position to continue using Firestore.

For timestamps in Javascript, you can send a Javascript date object and it will be treated as a timestamp in Firestore.

For example: new Date()

Solution 2:[2]

While we are waiting for Pablo's feature request, one workaround is to make a trigger that converts strings to timestamps on each creation or update. This would slow down a production database though, so you may want to turn it off once you are done with import.

import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
import {firestore} from "firebase-admin";
import Timestamp = firestore.Timestamp;

const listenPath = "/temp/{id}";

export const temp_onCreate = functions.firestore.document(listenPath).onCreate(async (snapshot, context) => {
    const id = context.params.id;
    await fixTypes(id, snapshot.data());
});

export const temp_onUpdate = functions.firestore.document(listenPath).onUpdate(async (change, context) => {
    const id = context.params.id;
    await fixTypes(id, change.after.data());
});

async function fixTypes(id: string, map: any): Promise<void> {
    const dateTime = map['walkdate'];
    const set = new Map<string, any>();

    if (typeof dateTime === 'string') {
        set.set('walkdate', Timestamp.fromDate(new Date(dateTime)));
    }

    if (set.size === 0) return;
    await admin.firestore().doc(`temp/${id}`).update(Object.fromEntries(set));
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Alexey Inkin