我想使用mongoose自定义类型的强大功能,但有一个问题我无法找到解决方法 . 基本上我们需要使用以下模式将时区保留为日期
{
date: {type: Date}, //UTC date for ease of use
zone: {type: String} //Initial timezone that allows to restore local date
}
我已经使用 cast
函数绘制了自定义类型LocalDate,该函数返回标准日期字符串 2014-10-24T14:00:00+0500
的 {date: , zone: }
对象(不确定这是否有效,因此欢迎提出任何建议) . 问题是给出以下代码
//Schema is extended with LocalDate already
var test = new Schema({
birthday: {type: Schema.Types.LocalDate}
});
var doc = new test({birthday: '2014-10-24T14:00:00+0500'});
doc.save(function(err){
//err is null here.
});
文档已插入数据库并具有_id . 但生日路径根本没有保存 .
看起来好像从未调用 cast
. 这里定义了's how it'
module.exports = function(mongoose){
var Schema = mongoose.Schema;
var Types = mongoose.Types;
var SchemaType = mongoose.SchemaType;
function LocalDate(){
SchemaType.call(this, key, options);
}
LocalDate.prototype.__proto__ = SchemaType.prototype;
//Here comes checkRequired, $conditionalHandlers etc. which seem to be irrelevant here
LocalDate.prototype.cast = function(val, scope, init){
console.log('casting LocalDate'); //Never logged
if (null === val || '' === val) return null;
if (_.isObject(val)){
return fromObject(val);
}
throw new SchemaType.CastError('LocalDate', val);
};
Schema.Types.LocalDate = LocalDate;
Types.LocalDate = LocalDate;
return LocalDate;
}
知道这里有什么问题吗?