How to keep date from client saved in MongoDB as d

2019-07-21 15:23发布

问题:

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?

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

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

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

回答1:

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.

Example:

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