文档提到了四种类型的时间相关字段类型(http://mongoid.org/en/mongoid/docs/documents.html#fields)。在其他数据库中,我可以看到这些字段将如何成为数据库中的不同类型,但对于 MongoDB 来说,它们不是都是日期类型吗?这仅仅是为了与 ActiveRecord 保持一致吗?
它们之间几乎没有区别,它们都包装了时间类型。您可以更改日期时间,日期或时间与区域,以便在从mongo反序列化后获取此类型的实例。
Mongoid 扩展了此类以添加用于数据绑定的 demongoize/mongoize 方法。所以唯一的区别在于实施。
所以时间实现
def demongoize(object)
return nil if object.blank?
object = object.getlocal unless Mongoid::Config.use_utc?
if Mongoid::Config.use_activesupport_time_zone?
object = object.in_time_zone(Mongoid.time_zone)
end
object
end
def mongoize(object)
return nil if object.blank?
begin
time = object.__mongoize_time__
if object.respond_to?(:sec_fraction)
::Time.at(time.to_i, object.sec_fraction * 10**6).utc
elsif time.respond_to?(:subsec)
::Time.at(time.to_i, time.subsec * 10**6).utc
else
::Time.at(time.to_i, time.usec).utc
end
rescue ArgumentError
EPOCH
end
end
日期实现
def demongoize(object)
::Date.new(object.year, object.month, object.day) if object
end
def mongoize(object)
unless object.blank?
begin
time = object.__mongoize_time__
::Time.utc(time.year, time.month, time.day)
rescue ArgumentError
EPOCH
end
end
end
您可以检查其他实现
https://github.com/mongoid/mongoid/blob/master/lib/mongoid/extensions/date.rb#L46https://github.com/mongoid/mongoid/blob/master/lib/mongoid/extensions/date_time.rb#L49https://github.com/mongoid/mongoid/blob/master/lib/mongoid/extensions/time.rb#L48https://github.com/mongoid/mongoid/blob/master/lib/mongoid/extensions/time_with_zone.rb#L32
上级:
抱歉链接已过时,因为它们指向主分支