I've been trying since long to figure out the best way to store user-defined date and time in MongoDB using mongoose library. What I mean by user-defined is that it could be a date/time from future or past. I don't want to store time stamp or current date. In some cases, I just need to store Time in 24hr Format because of some calculations and in some cases, I just want to store Date. I am using mongo and mongoose for the first time and its hard to find the correct way doing it. Although I have tried couple of methods which are as follows:
I stored the date and time in String format which is the easiest way of storing and retrieving I guess but the problem is I have to work alot in order to perform calculations and updating records back. Also, high chance of inaccuracy.
I tried the Date Schematype but almost everyother question & tutorial I found on goolgle/stack is just explaing the current date or timestamp problem. I tried using it but then I encounter a strange problem like
I am posting Date data in this format through a Post service, Though I just need the time in this case but it was prompting me a format error which make sense as well so I decided to capture the date just to avoid it,
"wakeupTime" : "2018/05/08 04:30:00",
"sleepTime" : "2018/05/07 19:30:00"
This is how I am recieving and creating my data
wakeupTime : new Date(req.body.wakeupTime),
sleepTime : new Date(req.body.sleepTime),
But It is storing this data in db with its own values I am not sure why
"wakeupTime": "2018-05-07T18:30:00.000Z",
"sleepTime": "2018-05-07T09:30:00.000Z",
In schema defination I have my wake up time and sleep time like this
wakeupTime: {
type: Date
},
sleepTime : {
type: Date
}
I know that dates could be very tricky and hard to grasp in the first place and I am very much sure that I am missing some pieces of this puzzle. I would really appreciate any help which could lead me to a accurate solution.
Dateso that is what it converts the string to. You really don't want to change that. Strings are bad news for queries and all kinds of usefulness that is generally applicable to dates. So you would be killing that, and wasting a lot of space in your database at the same time.Dateobjects are good. Learn to accept that.Number, and that is what you should be sending. The actual format is a matter of opinion, but you certainly don't want aDate, and nor should you be sending one. If you need to get time of day from aDateobject, then that's a different question.wakeupfield as number, you could create a virtual field calledwakeupTimeto formatwakeupinto time format and converting it into number when you are storing data