Reputation: 133
I have to make an appointment system for doctors using MEAN stack. in my Schema I've to store the start time and end time of a slot. Mongoose has no data type to store time.What data type should I use to store time?
Upvotes: 4
Views: 41463
Reputation: 1183
No direct solution for time only scenarios. Being forced to use Date isn't always applicable. Using type string with a custom validation using regex is what I decided to use.
classTiming: {
type: String,
validate: {
validator: function (v) {
if (!v) {
return true;
}
return /([01]?[0-9]|2[0-3]):[0-5][0-9]/.test(v);
},
message: (props) => `${props.value} is not valid time!`,
},
},
Time seems to be an ignored type. Whether its zod or joi, both needed a regex approach at the time of writing this:
classTiming: z
.string()
.regex(/([01]?[0-9]|2[0-3]):[0-5][0-9]/)
.optional()
.or(z.literal("")),
classTiming: Joi.string()
.regex(/([01]?[0-9]|2[0-3]):[0-5][0-9]/)
.empty(""),
Upvotes: 1
Reputation: 1588
You can set the timestamps
property to true
when defining a Schema and mongoose will add a createdAt
and updatedAt
field for you. Mongoose will also update the updatedAt
field for you when you do any update operation.
var schema = new Schema({
// ... Schema properties
}, {
timestamps: true
});
http://mongoosejs.com/docs/guide.html#timestamps
Upvotes: 11
Reputation: 312095
The Date
schema type of Mongoose represents not just a date, but a full date and time timestamp, so that would be the logical choice.
var slotSchema = new Schema({
startTime: Date,
endTime: Date,
...
});
Upvotes: 27
Reputation: 156
The Date object stores a specific moment down to the millisecond.
See: http://www.robertprice.co.uk/robblog/2011/05/javascript_date_time_and_node_js-shtml/
For more information on mongoose: http://mongoosejs.com/docs/guide.html
Upvotes: 2