9

In my web project using angular, node and mongodb with JSON, date is not natively supported by JSON serializer. There is a workaround for this problem, as shown here. However, I wonder what's the benefit saving the date as a date object instead of a string in MongoDB? I'm not that far with the project so I don't see the difference.

Community
  • 1
  • 1
newman
  • 6,841
  • 21
  • 79
  • 126
  • 1
    Angular is nodejs as such it should be using the MongoDB nodejs driver which will serialise ISODate into a JavaScript equaliviant. – Sammaye Apr 10 '15 at 15:26
  • 1
    @Sammaye uhm... angular is not nodejs. typo? – Kevin B Apr 10 '15 at 15:27
  • @KevinB so why does it have a nodejs install guide for it: https://docs.angularjs.org/tutorial ? – Sammaye Apr 10 '15 at 15:27
  • @KevinB But it runs the dev sever from npm? – Sammaye Apr 10 '15 at 15:30
  • @Sammaye I'm using nodejs driver for MongoDB and it turns date to string, see my other quesiton at `http://stackoverflow.com/questions/29505968/how-to-keep-date-from-client-saved-in-mongodb-as-date`. – newman Apr 10 '15 at 15:35

2 Answers2

16

By saving your dates not as dates but as strings, you are missing out on some very useful features:

  1. MongoDB can query date-ranges with $gt and $lt.
  2. In version 3.0, the aggregation framework got many useful aggregation operators for date handling. None of those work on strings and few of them can be adequately substituted by string operators.
  3. MongoDB dates are internally handled in UNIX epoch, so nasty details like saving timestamps from different timezones or daylight saving times are a non-issue.
  4. A BSON Date is just 8 byte. A date in the minimal form of YYYYMMDD is 12 byte (strings in BSON are prefixed with a 4 byte integer for the length). When you store it as an ISODate string which uses all the ISO 8601 standard has to offer (date, time accurate to millisecond and timezone), you have 32 byte - four times the storage space.

You need to know if any of this matters for your project.

When you really want to avoid using the BSON Date type, you should consider to store your dates as a number representing the elapsed milliseconds/seconds/hours/days (whatever appropriate for your use-case) since a fixed point in time instead of a string. That way you retain the advantages of everything but point 2.

Philipp
  • 67,764
  • 9
  • 118
  • 153
4

You should at least use ISO dates if you go for this approach. I would however argue that there are benefits in storing date values as date objects. Storing dates as date objects will allow you to add indices and should also help with date range queries. Saying this many developers seem to be happy to store dates as strings, see What is the best way to store dates in MongoDB?

Community
  • 1
  • 1
Alex
  • 21,273
  • 10
  • 61
  • 73