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

Behaviour of calling reorder method on Mongoid::Criteria

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 6.0.0
    • Affects Version/s: None
    • Component/s: None
    • Labels:
      None

      I'm using Rails 4.0.8, Ruby 2.1.2 and Mongoid 4.0.0 with Mongodb 2.6.3.<br />
      Let's assume I have the following Mongoid::Criteria that is using a default scope which sorts the documents:

      tracks = Track.where(:max_speed.gt => 60)
      => #<Mongoid::Criteria
        selector: {"max_speed"=>{"$gt"=>60}}
        options:  {:sort=>{"start_time"=>-1}}
        class:    Track
        embedded: false>
      

      Calling reorder on tracks returns a criteria without sorting options, which is what I would have expected:

      tracks.reorder
      => #<Mongoid::Criteria
        selector: {"max_speed"=>{"$gt"=>60}}
        options:  {}
        class:    Track
        embedded: false>
      

      The problem is that reorder not only returns a criteria without ordering options, but also modifies the original tracks variable by removing the sorting options:

      tracks
      => #<Mongoid::Criteria
        selector: {"max_speed"=>{"$gt"=>60}}
        options:  {}
        class:    Track
        embedded: false>
      

      So reorder behaves more like a reorder! function if I understand it correctly. I know that I can use tracks.apply_default_scope to restore the original sorting options, but that feels like an unnecessary extra step.<br />
      The unscoped method behaves just the way I would expect it: it returns an unscoped criteria, but does not change the variable it is being called on.

      tracks = Track.where(user_id: "some_id")
      => #<Mongoid::Criteria
        selector: {"user_id"=>"some_id"}
        options:  {:sort=>{"start_time"=>-1}}
        class:    Track
        embedded: false>
      
      tracks.unscoped
      => #<Mongoid::Criteria
        selector: {}
        options:  {}
        class:    Track
        embedded: false>
      
      tracks
      => #<Mongoid::Criteria
        selector: {"user_id"=>"some_id"}
        options:  {:sort=>{"start_time"=>-1}}
        class:    Track
        embedded: false>
      

      So is modifying the original variable really the intended behaviour of the reorder method?

      Regards,
      Carsten

            Assignee:
            emily.stolfo Emily Stolfo
            Reporter:
            cahlf cahlf
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: