Reputation: 73649
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
Reputation: 19372
I'm using:
dateOfBirth: { type: Object }
and saving like:
dateOfBirth: {year: 1988, month: 0, day: 8}
this gives me:
ability to search by year
, month
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):
Cons:
Upvotes: 5
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