-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathformatdate.js
More file actions
48 lines (38 loc) · 1.11 KB
/
formatdate.js
File metadata and controls
48 lines (38 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var mongoose = require('mongoose'),
SchemaTypes = mongoose.SchemaTypes || mongoose.Schema.Types,
CastError = mongoose.SchemaType.CastError;
var moment = require('moment');
/**
* FormatDate
*/
function FormatDate(path, options) {
SchemaTypes.Date.call(this, path, options);
this.validators.push([function(v) {
return v instanceof Date;
}, 'format']);
}
FormatDate.prototype = Object.create(SchemaTypes.Date.prototype);
FormatDate.prototype.cast = function(value) {
if (value === null || value === '') {
return null;
}
if (value instanceof Date) {
return value;
}
if (value instanceof Number ||
'number' == typeof value ||
String(value) == Number(value)) {
// support for timestamps
return new Date(Number(value));
}
// format date string
var format = this.options.format || 'YYYY-MM-DD';
var mdate = moment(value.toString() || '', format);
if (mdate.format(format) != value) {
// @todo hmmm....
//throw new CastError('formatdate', value);
return value;
}
return mdate.toDate();
};
module.exports = mongoose.Schema.Types.FormatDate = FormatDate;