Mongoose how to set date format in model

I am new to mongoose. I am using "Date" as the type for the "holidayDate" column . I only want to store the date not the time in the "holidayDate" column , so there is a way to define the date format in the domain model, so when my domain stores my "holidayDate" the column value will be stored according to the date format of the 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);

      

+5


source to share


2 answers


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



As a result, you will have to handle it in your code, ensuring that the time is always set (for example) 00:00:00 when inserting and querying, or by storing it as a different type (like a yyyy-mm-dd

or an integer). Which one is most appropriate will depend on your requirements for requesting and using that date.

+4


source


From the docs, if your schema has a date type field like

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

      

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



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

holiday.holidayDate instanceof Date; // true

      

and an invalid date will result in a CastError when validating the document.

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

holiday.holidayDate instanceof Date; // false
holiday.validateSync().errors['lastActiveAt']; // CastError

      

0


source







All Articles