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".
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
The Date SchemaType configures MongoDB to store the date as a BSON native Date object in our database. An example is shown below: ISODate("1990-01-01T23:00:00Z") The example above shows how Date is stored in a MongoDB database.
Basically you have two options: Save time in type: String. Save date time in type: Date.
Simply use: new Date("<YYYY-mm-dd>"); Which returns the ISODate with the specified date without a timestamp. MongoDB uses the ISO-8601 date notation, to represent date objects.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With