Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 654
Piyush Chaudhari Avatar asked May 28 '15 07:05

Piyush Chaudhari


People also ask

What is Date format in Mongoose?

The Date SchemaType configures MongoDB to store the date as a BSON native Date object in our database. An example is shown below: ISODate("1990-01-01T23:00:00Z") The example above shows how Date is stored in a MongoDB database.

How do I change the Date format in MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.

Can I set default value in Mongoose schema?

You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.

What is timestamps in Mongoose schema?

Timestamps save the current time of the document created and also when it was updated in form of a Date by turning it true. When set to true, the mongoose creates two fields as follows: createdAt: Date representing when the document was created. updatedAt: Date representing when this document was last updated.


1 Answers

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.

like image 138
Mark Hughes Avatar answered Oct 25 '22 21:10

Mark Hughes