1

I have the following code.

const Price = mongoose.model('Price', new mongoose.Schema({
  dateFrom: {
    type: Date,
    required: true
  },
  dateTo: {
    type: Date,
    required: true
  }
}));

In the database they are stored with the format i.e 2018-12-29T00:00:00.000Z. What I would like to do is to store the as 2018-12-29. Is there any way to do this?

Giannis
  • 312
  • 2
  • 5
  • 16

1 Answers1

0

You can manipulate the sent value this way. I hope it works

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
}


const Price = mongoose.model('Price', new mongoose.Schema({
    dateFrom: {
      type: String,
      required: true,
      set: date => formatDate(date)
    },
    dateTo: {
      type: String,
      required: true,
      set: date => formatDate(date)
    }
}));
Minan
  • 807
  • 7
  • 17
  • I still get the 2018-12-29T00:00:00.000Z format.. – Giannis Mar 01 '19 at 00:39
  • You can change the type value by replacing it with 'String' – Minan Mar 01 '19 at 00:53
  • 1
    @Minan Don't store dates as "string". Even as a "string" of `YYYYMMDD` that's still many bytes more storage than the internal 64-bit integer format of a BSON Date. – Neil Lunn Mar 01 '19 at 11:14
  • @Neil Lunn Yes, you are absolutely right. but is there any other way to record it this way? Perhaps it will be more correct to correct it only when it is requested. The 'get' method is available for this – Minan Mar 01 '19 at 17:01
  • The "any other way" is covered in the existing answers which have been here for a very long time, and that this question has been marked in duplicate of. I suggest you take at look at them yourself as well. – Neil Lunn Mar 01 '19 at 21:15