本文介绍了如何保持从保存在MongoDB中的日期客户日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的Node.js和Angular.js对于web项目。我明白,如果它在服务器上使用新的日期创建日期保存为日期()(例如: 2015-04-09 04:15:18.712Z 在Robomongo显示为Date类型)。但是,如果使用新的Date()客户端创建日期,它然后保存为一个字符串(如 2015-04-07T04:58:12.771Z 在Robomongo所示为String类型),因为它变成通过节点API的字符串。如何使保存为一个日期,而不是​​字符串?

I'm using Node.js and Angular.js for a web project. I understand that date is saved as date if it's created on server using new Date() (e.g. 2015-04-08 04:15:18.712Z shown in Robomongo as Date type). However, if the date is created on client using new Date(), it is then saved as a string (e.g. 2015-04-07T04:58:12.771Z shown in Robomongo as String type), because it becomes a string through node API. How to make it save as a Date instead of String?

更新:
这是我得到基于杰森卡斯特的输入内容。在节点的server.js指定齐磊选项,如下所示:

UPDATE:This is what I got based on Jason Cust's input. In node's server.js specify the reviver option as follows:

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

这将当数据从客户端发送到服务器自动将所有日期字符串的Date对象。

This will automatically converts all date strings to date objects when data is sent from client to server.

如果你想要做同样的事情的Angular.js客户,我找到了一个好博客安德鲁·戴维的

If you want to do the same thing for the Angular.js client, I found a good blog by Andrew Davey Automatic JSON date parsing with AngularJS

推荐答案

我要假设你使用JSON从您的角度应用程序发送的日期到您的节点的应用程序。该不将其插入MongoDB的重组前一个Date对象,所以你必须自己先做到这一点

I am going to assume you are using JSON to send the date from your Angular app to your Node app. The JSON spec doesn't reconstitute a Date object so you will have to do it yourself first before inserting it into 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) }

这篇关于如何保持从保存在MongoDB中的日期客户日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 17:37