0

The problem deals with mongoid / moped DATE type insertion. My code is below

s=Moped::Session::new(["127.0.0.1"])
s.use "test"
s["a"].insert mydate: Date.strptime("10/02/2014","%m/%d/%Y")

raises an error

# => undefined method `__bson_dump__' for Thu, 02 Oct 2014:Date

Why does Date type fails to insert into mongoDB via moped? I am pretty sure that mongoDB does support Date type.

Thank you for the help.

1 Answers1

2

MongoDB supports BSON type UTC datetime, in Moped this is mapped to Ruby Time, not Date. However, there is a very easy solution for your code, as Mongoid provides the Date#mongoize convenience function. Hope that this is what you want and that it helps.

date_mongoize.rb

require 'moped'
require 'mongoid'

s=Moped::Session::new(["127.0.0.1"])
s.use "test"
s["a"].find.remove_all
s["a"].insert mydate: Date.strptime("10/02/2014","%m/%d/%Y").mongoize
p s["a"].find.to_a

$ ruby date_mongoize.rb

[{"_id"=>"5272a943fa23bace4f7650e3", "mydate"=>2014-10-02 00:00:00 UTC}]
Gary Murakami
  • 3,392
  • 1
  • 16
  • 20
  • this works like a magic! I never thought that Date in mongodb is not Date in ruby, but instead a Time. Mongoize method works as expected. Thank you. – Yudho Ahmad Diponegoro Nov 03 '13 at 04:26
  • 1
    You're welcome, glad to help. If you need more details for types in MongoDB, the BSON spec is a good reference - http://bsonspec.org/ – Gary Murakami Nov 04 '13 at 00:58