Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-2535

`find` should support _ids of type hash, array etc.

    • Type: Icon: Task Task
    • Resolution: Done
    • 3.1.0
    • Affects Version/s: None
    • Component/s: None
    • Labels:

      Didn't get much love on the google group about this, so thought I'd go straight for it and open an issue (I do think it's something that should be supported - stuff like this is one of the useful features of mongodb).

      Mongodb allows primary keys (_id field) of any type, including Hash and Array. The problem:

      class Foo
        include Mongoid::Document
        field :_id, :type => Hash
      end
      
      f = Foo.create! {|f| f.id = {a: 1, b: 2} } # don't forget _id attr_protected-ness!
      Foo.first.id
       => {"a"=>1, "b"=>2} # all good so far, but...
      Foo.find({"a"=>1, "b"=>2})
       => [#<Foo _id: {"a"=>1, "b"=>2}, _type: nil>] # an array!
      

      This is because Mongoid is seeing the _id hash as "resizable", and inferring that you're looking for multiple documents, as you would be in the more common case:

      Bar.find([1, 2, 3])
      => [#<Bar _id: 1>, #<Bar _id: 2>, #<Bar _id: 3>]
      

      This is a change of behaviour between v2 and v3 that isn't mentioned in the release notes, so may be accidental..?

      But I think this is not too hard to fix, because Mongoid also knows the type of the id field, so it can apply logic like "if my _id field is a hash, and find has received a hash, then I'm looking for one document. If find receives an _array of hashes, only then is it multiple documents" etc. But I suppose this is an api change, so would have to wait for 4.0... even though it was unintentional (maybe)?

            Assignee:
            durran Durran Jordan
            Reporter:
            bensymonds Ben Symonds
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: