8

I have been trying to save the date from javascript side into MongoDB in ISODate format. But it just saves the date field in my MongoDB document in string format.

Here is the object I'm sending into the MongoDB to be saved as a document in a given collection.

var currentDate = new Date();

postData = {
   deviceID: deviceID,
   companyID: companyID,
   userID: userID,
   date: currentDate
};

Everything works fine except the date field is just saved in String format. Couldn't find any SO question which could give a clear answer for this problem as well, if there is a one please direct me to the proper place!

Ravindu Nirmal Fernando
  • 4,272
  • 4
  • 18
  • 29
  • This may help http://stackoverflow.com/questions/21286599/inserting-and-querying-date-with-mongodb-and-nodejs – chridam Feb 21 '17 at 19:14

2 Answers2

9

I solved this by handling this in my Node JS API side. The real problem is I've been sending this to the API as an stringified JSON object. though it was set as a new Date() object it get stringified.

So within my Node JS API side before inserting it into the MongoDB collection I've done this,

var data = req.body.postData;
var date = data[0].date;
var dateObject = new Date(date);
date[0].date = dateObject;

Which did the trick! Thanks for the answers!

Ravindu Nirmal Fernando
  • 4,272
  • 4
  • 18
  • 29
1

You can try this:

var currentDate = new Date();

postData = {
   deviceID: deviceID,
   companyID: companyID,
   userID: userID,
   date: currentDate.toISOString()
};

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString

Vladimir M
  • 4,403
  • 1
  • 19
  • 24
  • Thanks for the comment, but I tried this too. It still the same, just a String is being saved as the date field. – Ravindu Nirmal Fernando Feb 21 '17 at 19:16
  • @RavinduFernando hmm... ok. I guess then the question is a bit different then how I read it. I am not familiar with mongo internals, but accepted answer to this question may indicate that what you see is not exactly what is stored: http://stackoverflow.com/questions/10908159/why-does-mongo-store-my-date-as-a-string – Vladimir M Feb 21 '17 at 19:34
  • 1
    May thanks for the point - But I also went through that answer before. but the real problem is I want do Mongo DB grouping based on the **date** value, but since its not in date type the Mongo DB grouping doesn't work as expected. But when I updated the field value using Robo Mongo client as ISODate and convert date field to Date type the grouping works fine. That's why I really wants to find a way which I can save the date straight in ISODate format. – Ravindu Nirmal Fernando Feb 21 '17 at 19:57