Saurabh
Saurabh

Reputation: 73649

How to save only date part with mongoose, not in ISODate format

How do I save only date part with mongoose schmea. Currently my model is like this:

myDate: { type: Date}

Which saves date as "2016-02-27T00:00:00.000Z" even if I pass only: "2016-02-27".

Upvotes: 6

Views: 7557

Answers (2)

num8er
num8er

Reputation: 19372

I'm using:

dateOfBirth: { type: Object }

and saving like:

dateOfBirth: {year: 1988, month: 0, day: 8}

this gives me:

  1. ability to search by year, month

  2. ability to make date object:

    const dateOfBirth = new Date(
      user.dateOfBirth.year, 
      user.dateOfBirth.month, 
      user.dateOfBirth.day
    );
    

which will avoid timezone shiftings, since date object will be created on device's environment


UPD

P.S. I was not writing pros and cons since my answer was about alternative way of storing date separately and it should be obvious when this approach used.

After chatting with SergiiStotskyi in comments below I decided to put pros and cons to warn devs to choose best solution.

Keep in mind this approach has very few benefit(s).

Pros (I could find only two):

  1. separate year, month, day fields helps to filter by exact year, month, day. Like: find all records for May month grouped by Year (to compare differences for months for previous years).
  2. in comparison with Date which sensitive to timezone, year, month, day is does not shift by timezone
  3. not exactly benefit, date can be saved as it comes from client-side if every element date was separate too

Cons:

  1. If needed to get records by age it will be hard to determine, will require approximation used by year field (which in my use cases fits best, since no-one cares exact numbers in my project)
  2. For exact age filtering will require aggregate with matching by year and reducing by filtering out of range items
  3. Need to validate leap year

Upvotes: 5

L. Meyer
L. Meyer

Reputation: 3253

Behind the scene, a mongoose date is just like a date in javascript : it stores hours, seconds etc... There is no distinction with date/datetime like in SQL. In for a penny, in for a pound. That being said, it just a matter of display.

The reason is that mongo doesn't support this kind of type. You could create an object with year/month/day properties but it would be a pain to deal with.

Upvotes: 3

Related Questions