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

I am trying to save a date with javascript in MongoDB in ISODate format. But it just saves the date field in my MongoDB document in string format.

Here is the object that I submit to MongoDB to save as a document in this collection.

var currentDate = new Date();

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

Everything works fine, except that the date field is simply saved in String format. Could not find any question that could give a clear answer to this problem, if there is, please direct me to the right place!

+4
source share
2 answers

, API- Node JS API. , API JSON. Date(), .

, API- Node JS API, MongoDB, ,

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

! !

+5

:

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

+1

Source: https://habr.com/ru/post/1670458/


All Articles