Piotr Stulinski
Piotr Stulinski

Reputation: 9471

saving a clientside date as UTC date object into Mongo

I am trying to save a date into meteor mongodb my challenge is as follows: 1) if i use new Date() it creates a date object in mongo DB however it saves the time as local time as javascript Date() this always comes with a timezone +0x:hours based on browser local timezone. When i retrieve this it causes havoc as i am assuming everything in my db is UTC.

2) I want to use moment js library which is great because it can represent dates in UTC properly but my challenge is how do i get mongo db to accept a moment time? The minute i use moment.format() it saves it as a string!

So how can i send a date to a mongodb insert command with a date object that is in UTC? string just dont work :(

Any help would be appreciated.

Thanks

Upvotes: 4

Views: 5513

Answers (3)

Andrew Mao
Andrew Mao

Reputation: 36920

The Meteor community recently started an extensive document about how to use dates and times. You'll find a lot of useful information there, in addition to David Weldon's links:

https://meteor.hackpad.com/Meteor-Cookbook-Using-Dates-and-Times-qSQCGFc06gH

However, in particular I recommend using https://github.com/mizzao/meteor-timesync when security is not a concern. It allows you to client-locally obtain an accurate server time even if the client's clock is way off, without a round-trip to the server. This can be useful for all kinds of reasons - in my apps, I universally just use server-relative time and don't care about what the client's time is at all.

Upvotes: 0

Hubert OG
Hubert OG

Reputation: 19544

The problem with saving dates on the client is that each client can have a different time zone, or even wrong time set. Thus the only solution is to have the date set on the server. Using a method for each insert / update is not an elegant solution.

A common practice is to modify the document inside allow or deny callback:

Messages.allow({
  insert: function(userId, doc) {
     ...
     doc.timestamp = new Date();
     return true;
  },
});

That way you ensure all documents have a compatible timestamp, and you can use usual db methods on the client.

Upvotes: 0

David Weldon
David Weldon

Reputation: 64332

I think everything you need to know about both of these questions can be found here and here.

TLDR:

  • If you directly insert/update from the client you will store a timestamp based on the user's clock. It will still be stored as UTC, but you may or may not want to trust that the time is correct. I strongly suggest using a method for any db modifications which involve time so that the server's version of time will always be used.

  • Moment objects are not serializable to a format compatible with mongodb. Use a date object and format it on the client.

Upvotes: 4

Related Questions