如何保存date保存在MongoDB中的客户端date?

我正在使用Node.js和Angular.js为一个Web项目。 我知道date是保存为date,如果它是在服务器上使用新的date()(例如2015-04-08 04:15:18.712Z在Robomongo中显示为datetypes)创build的。 但是,如果在客户端使用新的Date()创builddate,则会将其保存为一个string(例如2015-04-07T04:58:12.771Z在Robomongo中显示为Stringtypes),因为它通过节点API 。 如何使它保存为date而不是string?

更新:这是我得到的基于Jason Cust的input。 在节点的server.js中指定reviver选项,如下所示:

 app.use(bodyParser.json({ reviver: function(key, value) { if ( typeof value === 'string' && value.length === 24) { if (value.match(/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/)){ return new Date(value); } } return value; }})); 

当数据从客户端发送到服务器时,这将自动将所有datestring转换为date对象。

如果你想为Angular.js客户端做同样的事情,我发现一个由Andrew Davey编写的好博客用AngularJS自动JSONdate分析

我将假设您使用JSON将您的Angular应用程序的date发送到您的Node应用程序。 JSON规范不重构Date对象,因此在将其插入到MongoDB之前,您必须先自己做。

例:

 // simulate JSON from HTTP request var json = JSON.stringify({date: new Date()}); console.log(json); // outputs: '{"date":"2015-04-08T04:50:04.252Z"}' var obj = JSON.parse(json); console.log(obj); // outputs: { date: '2015-04-08T04:50:04.252Z' } // reconstitute Date object obj.date = new Date(obj.date); console.log(obj); // outputs: { date: Wed Apr 08 2015 00:50:04 GMT-0400 (EDT) }