ruby-on-railsrubymongodbmongoidmoped

Mongoid / Moped Date Type Insertion Failure


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.


Solution

  • 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}]