Bug? Saving Date to collection modifies milliseconds

I receive timestamps from another system which I need to save to a Meteor collection. These timestamps should be accurate to the second, however, everything I’ve tried adds a random millisecond value to the collection, which then messes up subsequent queries. For example:

MyData.insert({ts: new Date('2020-01-01T00:00:00.000Z')})

Is saved to the database as:

    "_id" : "Z33ezuxtBmRnwofur", 
    "ts" : ISODate("2020-01-01T00:00:00.342+0000") //Note: milliseconds value

I’ve also tried the following to no avail:

MyData.insert({ts: moment('2020-01-01T00:00:00.000Z').toDate()})
MyData.insert({ts: moment('2020-01-01T00:00:00.000Z').unix()})
MyData.insert({ts: moment('2020-01-01T00:00:00.000Z').valueOf()})

I see the MongoDB Docs say:


Internally, Date objects are stored as a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970).

Not all database operations and drivers support the full 64-bit range. You may safely work with dates with years within the inclusive range 0 through 9999 .

I know the issue is not on Mongo’s side (server v4.2.3), since I can perform insert queries using my MongoDB client (Studio 3T) outside of Meteor and milliseconds are properly saved. Is this due to the MongoDB driver that Meteor (v1.9) is using? Or am I missing something simple?

I suppose the work-around is to convert all those timestamps to signed 64-bit integers and save them that way, however I’d like to hear your thoughts on this.

1 Like

I know that new Date() is a constructor and is slower than Date.now() or other date functions. I don’t know if this could be the reason by I personally avoid the constructor and use Date.now(). https://jsperf.com/date-now-vs-new-date