7

I am new for mongoose. I am using "Date" as type for my "holidayDate" column. I want to store only date not time in my "holidayDate" column so is there any way to define date format in domain model so when my domain is save my "holidayDate" column value will save according to the date format of domain model.

var HolidaySchema = new Schema({
    holidayName: {
        type: String,
        default: '',
        required: 'Please fill holiday name',
        trim: true
    },
    holidayDate: {
        type: Date,
    required: 'Please fill From Date'
    }

});

mongoose.model('Holiday', HolidaySchema);
Piyush Chaudhari
  • 962
  • 3
  • 19
  • 41

2 Answers2

5

MongoDB's underlying storage engine (BSON) does not have a type for date-without-time, just full dates (see this page for details of the BSON types in the MongoDB documentation).

The upshot of this is you will need to handle it in your code by ensuring the time is always set to (for example) 00:00:00 when inserting and querying, or by storing it as a different type (for example a yyyy-mm-dd string, or an integer). Which of these is most appropriate would depend on your requirements to query and use that date.

Mark Hughes
  • 7,264
  • 1
  • 33
  • 37
-1

From the docs if in your schema you have a date type field e.g

 holidayDate: {
        type: Date,
    required: 'Please fill From Date'
    }

and when you create your holiday document, Mongoose will cast the value to a native JavaScript date using the Date() constructor

const holiday = new Holiday({
holidayDate:'2012-12-19'
});

holiday.holidayDate instanceof Date; // true

and an invalid date will lead to a CastError when you validate the document.

const holiday = new Holiday({
holidayDate:'invalid date'
});

holiday.holidayDate instanceof Date; // false
holiday.validateSync().errors['lastActiveAt']; // CastError
Deeksha Sharma
  • 3,199
  • 1
  • 19
  • 16