Reputation: 8509
How can I save DD/MM/YYYY format into mongodb database in date type?
After saving it into mongodb, when I retrieved, how can I convert it back to DD/MM/YYYY?
I am using Mongoose.
Upvotes: 0
Views: 1570
Reputation: 1348
Better way to store dates in mongodb is store them by using native javascript date object.
They allows you to use some useful methods (comparison, map reduce, ...) in mongodb natively.
Then, you can easily get formatted date by using mongoose virtuals
, e.x.:
// describe your schema
var schema = new Schema({
time: Date
}, {
toObject: { getters: true }
});
// schema.formatted_time -> DD/MM/YYYY
schema.virtual('formatted_time').get(function() {
var date = new Date(this.time);
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
});
Upvotes: 1