Feels weird to ask a question that’s been asked and answered before, but I did search before posting.
So I want to store a timestamp in Firestore but its either being stored as String or Map, but not as the Timestamp object.
new Date()
is stored as a StringTimestamp.fromDate(new Date())
or simplyTimestamp.now()
is stored as a Map (seconds and nanoseconds)
I’m importing the method like so:
const { Timestamp } = require("firebase/firestore");
Probably worth mention, this is a cloud function that I’m testing locally via node filename.js
What am I doing wrong?
2
Answers
Firestore does not store JavaScript Date objects. See Supported data types. It appears they store in sub-millisecond resolution high resolution time like
window.performance.now()
. You should be able to pass a JavaScriptDate
object as a value though withfirebase.firestore.Timestamp.fromDate(new Date());
Looking at the documentation on the Timestamp class, a Timestamp stores the date in a second or nanosecond format. Just like you noted, this is why you are not seeing a true Date object stored in the firebase.
In my general experience, I usually use dates stored as string or timestamp representations in a database. The service getting those date values must convert the fetched data into a data type the service can use. Below are a couple of examples for fetching and storing date data:
My recommendation would be to store dates in a Timestamp or string representation. Then in the service reading/writing that data, you should parse the data into a
Date
object on read and from aDate
object to the string/timestamp on a write.