Venkat
Venkat

Reputation: 19

How to save only date(yyy-mm-dd) in mongo using mongoose

I need to save the date in yyyy-mm-dd format, where has it adds timezone and the day value is decremented by one

Upvotes: 1

Views: 1109

Answers (1)

pr0p
pr0p

Reputation: 2358

In mongoose schema there is something called time stamps include it.

Schema({
    //your schema..
},{
    timestamps: true
})

When ever you extract the date and time it will be converted into local time zone and displayed. Still if you are not convinced you can add date object to your schema

date:{
    type: String,
    required: true
}

and you send the date object as follow:

var d = new Date();
var dateString = d.getFullYear() + '-';
if(d.getMonth()<9)
    dateString += '0' + (1+d.getMonth()) + '-';
else
    dateString += (1+d.getMonth()) + '-';

if(d.getDate()<10){
    dateString += '0' + d.getDate();
else
    dateString += d.getDate();

Use dateString for use in mongoose.

PS:Usage of timestamps is the best practice. It creates a createdAt and updatedAt fields which can be used in your front end to derive the dates.

Upvotes: 1

Related Questions