Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - How to save a date in MongoDB document in ISODate format?

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!

like image 900
Ravindu Nirmal Fernando Avatar asked Feb 21 '17 19:02

Ravindu Nirmal Fernando


People also ask

How are dates saved in MongoDB?

MongoDB will store date and time information using UTC internally, but can easily convert to other timezones at time of retrieval as needed.

Can we store date as string in MongoDB?

You can safely store dates as strings and query on them as long as they are properly formatted for date, i.e., “YYYY-MM-ddTHH:mm:ss”.

What is ISODate in JavaScript?

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss. sssZ , respectively). The timezone is always zero UTC offset, as denoted by the suffix Z .


2 Answers

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!

like image 130
Ravindu Nirmal Fernando Avatar answered Sep 18 '22 18:09

Ravindu Nirmal Fernando


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

like image 42
Vladimir M Avatar answered Sep 21 '22 18:09

Vladimir M