JavaScript-如何以ISODate格式在MongoDB文档中保存日期? [英] JavaScript - How to save a date in MongoDB document in ISODate format?

查看:158
本文介绍了JavaScript-如何以ISODate格式在MongoDB文档中保存日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将日期从JavaScript端以ISODate格式保存到MongoDB中.但这只是将日期字段以字符串格式保存在我的MongoDB文档中.

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.

这是我要发送到MongoDB中的对象,将其另存为给定集合中的文档.

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
};

一切工作正常,只不过日期字段只是以String格式保存.也找不到任何可以为该问题提供清晰答案的SO问题,如果有,请直接将我定向到正确的位置!

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!

推荐答案

我通过在Node JS API端进行处理来解决了这个问题.真正的问题是我已经将其作为字符串化的JSON对象发送到API.尽管它被设置为新的Date()对象,但它却被字符串化了.

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.

因此,在将它插入MongoDB集合之前,在Node JS API方面,我已经完成了

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!

这篇关于JavaScript-如何以ISODate格式在MongoDB文档中保存日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆