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

I have been trying to save the date from javascript side into MongoDB in ISODate format. But it just sa

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,
   panyID: panyID,
   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!

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,
   panyID: panyID,
   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!

Share Improve this question asked Feb 21, 2017 at 19:04 Ravindu Nirmal FernandoRavindu Nirmal Fernando 4,8624 gold badges20 silver badges31 bronze badges 1
  • This may help stackoverflow./questions/21286599/… – chridam Commented Feb 21, 2017 at 19:14
Add a ment  | 

2 Answers 2

Reset to default 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!

You can try this:

var currentDate = new Date();

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743645526a4483691.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信