# File lib/mongo/cursor.rb, line 103
    def next
      if @cache.length == 0
        if @query_run && (@options & OP_QUERY_EXHAUST != 0)
          close
          return nil
        else
          refresh
        end
      end
      doc = @cache.shift

      if doc && doc['$err']
        err = doc['$err']

        # If the server has stopped being the master (e.g., it's one of a
        # pair but it has died or something like that) then we close that
        # connection. The next request will re-open on master server.
        if err.include?("not master")
          @connection.close
          raise ConnectionFailure.new(err, doc['code'], doc)
        end

        raise OperationFailure.new(err, doc['code'], doc)
      end

      if @transformer.nil?
        doc
      else
        @transformer.call(doc) if doc
      end
    end