Monoid dynamic crawler with Mongoid :: Errors :: DocumentNotFound exception thrown

I am creating a REST api for this project that uses Mongoid.

I set the following to catch the exception Mongoid::Errors::DocumentNotFound:

rescue_from Mongoid::Errors::DocumentNotFound in my base controller

In my controller, I have this request code:

@current_account.users.find(:first, :conditions => {:name => "some_name"})

The above query returns nil. This is not an exception. I tried another syntax:

User.find(:conditions => {:name => "same"}).first

All these methods just run whereinside, and afaik wheredoes not throw an exception, it just returns[]

So what could be the solution to this? I want a partially dynamic crawler, but should also throw an exception?

+5
source share
2 answers

, Mongoid DocumentNotFound find, ( ). . Mongoid:

# lib/mongoid/errors/document_not_found.rb

# Raised when querying the database for a document by a specific id which
# does not exist. If multiple ids were passed then it will display all of
# those.

, , - , DocumentNotFound ( ), ( ).

:

raise Mongoid::Errors::DocumentNotFound.new(User, params[:name]) unless @current_account.users.first(:conditions => {:name => params[:name]})

: , , (, , - !):

@current_account.users.where!(:conditions => {:name => params[:name]})

Mongoid::CollectionEmpty, , , . , , , , .

, , Mongoid::CollectionEmpty ( ).

# lib/mongoid_criterion_with_errors.rb
module Mongoid
  module Criterion
    module WithErrors
      extend ActiveSupport::Concern

      module ClassMethods
        def where!(*args)
          criteria = self.where(args)
          raise Mongoid::EmptyCollection(criteria) if criteria.empty?
          criteria
        end
      end
    end
  end

  class EmptyCollection < StandardError
    def initialize(criteria)
      @class_name = criteria.class
      @selector = criteria.selector
    end

    def to_s
      "Empty collection found for #{@class_name}, using selector: #{@selector}"
    end
  end
end

# config/application.rb
module ApplicationName
  class Application < Rails::Application
    require 'mongoid_criterion_with_errors'
    #...snip...
  end
end

# app/models/user.rb
class User
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Criterion::WithErrors
  #...snip...
end
+3

.

raise_not_found_error false. config/mongoid.yml

development:
  host: localhost
  port: 10045
  username: ...
  password: ...
  database: ...
  raise_not_found_error: false

http://mongoid.org/docs/installation/configuration.html

+6

All Articles