简体   繁体   中英

mongoose how to set date format in model

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);

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.

From the docs if in your schema you have a date type field eg

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM