구성
이 페이지의 내용
Mongoid는 일반적으로 옵션과 클라이언트를 지정하는 mongoid.yml
파일을 통해 구성됩니다. 가장 간단한 구성은 다음과 같으며, Mongoid가 'localhost:27017'에서 MongoDB 서버와 통신하고 'mongoid'라는 이름의 데이터베이스를 사용하도록 구성합니다.
development: clients: default: database: mongoid hosts: - localhost:27017
위의 예에서 구성 파일의 최상위 키인 development
는 애플리케이션이 실행 중인 환경 이름(예시: development
, test
또는 production
)을 나타냅니다. 위 예에서 세 번째 레벨 키인 default
는 Mongo 클라이언트 이름을 나타냅니다. 대부분의 애플리케이션은 default
라는 단일 클라이언트를 사용합니다.
기본 구성 생성
Ruby on Rails를 사용하는 경우 다음 명령을 실행하여 Mongoid에서 기본 구성 파일을 생성하도록 할 수 있습니다.
rails g mongoid:config
구성 파일이 config/mongoid.yml
에 배치됩니다.
Ruby on Rails를 사용하지 않는 경우 위에 제공된 최소 구성을 복사하여 config/mongoid.yml
로 저장할 수 있습니다.
Mongoid 구성 로드
Ruby on Rails를 사용하는 경우 애플리케이션이 로드될 때 Rails.env
에 저장된 현재 환경에 대한 Mongoid 구성이 자동으로 로드됩니다.
application.rb
에 다음을 추가하여 애플리케이션이 Mongoid가 되도록 ORM을 구성해야 할 수 있습니다.
config.generators do |g| g.orm :mongoid end
Ruby on Rails를 사용하지 않는 경우 Mongoid 구성을 수동으로 로드해야 합니다. 이 작업은 다음과 같이 구성 파일 경로를 인수로 사용하는 Mongoid.load!
메서드를 통해 수행할 수 있습니다.
# Use automatically detected environment name Mongoid.load!("path/to/your/mongoid.yml") # Specify environment name manually Mongoid.load!("path/to/your/mongoid.yml", :production)
Mongoid가 환경 이름을 자동으로 감지하라는 요청을 받으면 다음 소스를 순서대로 검사하여 이를 수행합니다.
Rails
최상위 상수가 정의되면Rails.env
가 됩니다.Sinatra
최상위 상수가 정의되면Sinatra::Base.environment
가 됩니다.RACK_ENV
환경 변수.MONGOID_ENV
환경 변수.
구성 파일을 사용하지 않고 Ruby에서 직접 Mongoid를 구성하는 것도 가능합니다. 이 구성 스타일은 환경 개념을 지원하지 않습니다. 어떤 구성이 제공되든 제공된 구성은 현재 환경에 적용됩니다. 그러나 여러 클라이언트를 정의하는 것은 지원합니다.
Mongoid.configure do |config| config.clients.default = { hosts: ['localhost:27017'], database: 'my_db', } config.log_level = :warn end
참고
Mongoid의 구성 요소를 사용하거나 참조하기 전에 Mongoid를 구성해야 합니다. 구성 요소가 사용되거나 참조되면 구성을 변경해도 이미 인스턴스화된 구성 요소에 변경 사항이 적용되지 않을 수 있습니다.
Mongoid 구성 옵션
다음 주석이 달린 예시 mongoid.yml
은 Mongoid를 구성하는 방법을 보여줍니다.
Mongoid는 클라이언트 구성을 위해 Ruby 드라이버로 위임합니다. 드라이버 옵션에 관한 자세한 내용은 드라이버 설명서에서 확인하세요.
development: # Configure available database clients. (required) clients: # Define the default client. (required) default: # A uri may be defined for a client: # uri: 'mongodb://user:password@myhost1.mydomain.com:27017/my_db' # Please see driver documentation for details. Alternatively, you can # define the following: # # Define the name of the default database that Mongoid can connect to. # (required). database: my_db # Provide the hosts the default client can connect to. Must be an array # of host:port pairs. (required) hosts: - myhost1.mydomain.com:27017 - myhost2.mydomain.com:27017 - myhost3.mydomain.com:27017 options: # These options are Ruby driver options, documented in # https://mongodb.com/ko-kr/docs/ruby-driver/current/reference/create-client/ # Change the default write concern. (default = { w: 1 }) write: w: 1 # Change the default read preference. Valid options for mode are: :secondary, # :secondary_preferred, :primary, :primary_preferred, :nearest # (default: primary) read: mode: :secondary_preferred tag_sets: - use: web # The name of the user for authentication. user: 'user' # The password of the user for authentication. password: 'password' # The user's database roles. roles: - 'dbOwner' # Change the default authentication mechanism. Please see the # driver documentation linked above for details on how to configure # authentication. Valid options are :aws, :gssapi, :mongodb_cr, # :mongodb_x509, :plain, :scram and :scram256 (default on 3.0 # and higher servers is :scram, default on 2.6 servers is :plain) auth_mech: :scram # Specify the auth source, i.e. the database or other source which # contains the user's login credentials. Allowed values for auth source # depend on the authentication mechanism, as explained in the server documentation: # https://mongodb.com/ko-kr/docs/manual/reference/connection-string/#mongodb-urioption-urioption.authSource # If no auth source is specified, the default auth source as # determined by the driver will be used. Please refer to: # https://mongodb.com/ko-kr/docs/ruby-driver/current/reference/authentication/#auth-source auth_source: admin # Connect directly to and perform all operations on the specified # server, bypassing replica set node discovery and monitoring. # Exactly one host address must be specified. (default: false) #direct_connection: true # Deprecated. Force the driver to connect in a specific way instead # of automatically discovering the deployment type and connecting # accordingly. To connect directly to a replica set node bypassing # node discovery and monitoring, use direct_connection: true instead # of this option. Possible values: :direct, :replica_set, :sharded. # (default: none) #connect: :direct # Change the default time in seconds the server monitors refresh their status # via hello commands. (default: 10) heartbeat_frequency: 10 # The time in seconds for selecting servers for a near read preference. (default: 0.015) local_threshold: 0.015 # The timeout in seconds for selecting a server for an operation. (default: 30) server_selection_timeout: 30 # The maximum number of connections in the connection pool. (default: 5) max_pool_size: 5 # The minimum number of connections in the connection pool. (default: 1) min_pool_size: 1 # The time to wait, in seconds, in the connection pool for a connection # to be checked in before timing out. (default: 1) wait_queue_timeout: 1 # The time to wait to establish a connection before timing out, in seconds. # (default: 10) connect_timeout: 10 # How long to wait for a response for each operation sent to the # server. This timeout should be set to a value larger than the # processing time for the longest operation that will be executed # by the application. Note that this is a client-side timeout; # the server may continue executing an operation after the client # aborts it with the SocketTimeout exception. # (default: nil, meaning no timeout) socket_timeout: 5 # The name of the replica set to connect to. Servers provided as seeds that do # not belong to this replica set will be ignored. replica_set: my_replica_set # Whether to connect to the servers via ssl. (default: false) ssl: true # The certificate file used to identify the connection against MongoDB. ssl_cert: /path/to/my.cert # The private keyfile used to identify the connection against MongoDB. # Note that even if the key is stored in the same file as the certificate, # both need to be explicitly specified. ssl_key: /path/to/my.key # A passphrase for the private key. ssl_key_pass_phrase: password # Whether or not to do peer certification validation. (default: true) ssl_verify: true # The file containing a set of concatenated certification authority certifications # used to validate certs passed from the other end of the connection. ssl_ca_cert: /path/to/ca.cert # Compressors to use. (default is to not use compression) compressors: [zlib] # Configure Mongoid-specific options. (optional) options: # Application name that is printed to the MongoDB logs upon establishing # a connection in server versions 3.4 or greater. Note that the name # cannot exceed 128 bytes in length. It is also used as the database name # if the database name is not explicitly defined. (default: nil) app_name: MyApplicationName # Type of executor for queries scheduled using ``load_async`` method. # # There are two possible values for this option: # # - :immediate - Queries will be immediately executed on a current thread. # This is the default option. # - :global_thread_pool - Queries will be executed asynchronously in # background using a thread pool. #async_query_executor: :immediate # Mark belongs_to associations as required by default, so that saving a # model with a missing belongs_to association will trigger a validation # error. (default: true) belongs_to_required_by_default: true # (Deprecated) Maintain broken behavior of sum over empty result sets for backwards # compatibility. When calculating a sum on a field with a null context, # for example: # # Product.none.sum(:price) # # ... return field name (`:price') instead of 0. # # When calculating a sum via a database query with an empty result set, # for example: # # Product.where(impossible_condition: true).sum(:price) # # ... return nil instead of 0. # (default: false) #broken_aggregables: true # (Deprecated) Ignore aliased fields in embedded documents when performing pluck and # distinct operations, for backwards compatibility. # (default: false) #broken_alias_handling: true # (Deprecated) Maintain broken `and' method behavior that existed in Mongoid 7.3 # and earlier for backwards compatibility: in some situations, conditions # already present in a Criteria object would be replaced by newer # conditions when `and' method is used instead of the new conditions # being added to the existing conditions. This would happen when using # the same operator on the same field multiple times. For example: # # Band.where(id: 1).and({year: {'$in' => [2020]}}, {year: {'$in' => [2021]}}).where(id: 2) # # yields the following criteria: # # <Mongoid::Criteria # selector: {"_id"=>1, "year"=>{"$in"=>[2020]}, "$and"=>[{"_id"=>2}]} # options: {} # class: Band # embedded: false> # # This is obviously incorrect as the {"$in"=>[2021]} clause is lost. # Notice that the clause is only lost when both clauses are added using # the #and method. # (default: false) #broken_and: true # (Deprecated) When exiting a nested `with_scope' block, set the current scope to # nil instead of the parent scope for backwards compatibility. # (default: false) #broken_scoping: true # (Deprecated) Maintain broken update behavior in some cases for backwards # compatibility. # # In Mongoid 7.3 and earlier, when assigning a value to an embedded # document, then setting it to nil, then assigning the original value # to it again, the second update would not work and the value for the # embedded document would remain nil. Take this case: # # canvas.palette = palette # canvas.palette = nil # canvas.palette = palette # # ... where canvas embeds_one palette. # # In Mongoid 7.3 and earlier, canvas.palette would be nil when we would # expect it to be palette. Set this option to true to keep this behavior, # set the option to false to perform the second update correctly. # (default: false) #broken_updates: true # (Deprecated) Time objects in Ruby have nanosecond precision, whereas MongoDB server # can only store times with millisecond precision. Set this option to # true to truncate times to millisecond precision when performing # queries on already loaded embedded associations (this is also called # "embedded matching" and is done completely in Ruby), to obtain the # same query results when performing time comparisons regardless of # which documents are being queried. Setting this option to false will # produce different results for queries on embedded associations that # are already loaded into memory vs queries on unloaded associations and # top-level models. (default: true) #compare_time_by_ms: false # Set the global discriminator key. (default: "_type") discriminator_key: "_type" # Raise an exception when a field is redefined. (default: false) duplicate_fields_exception: false # Defines how many asynchronous queries can be executed concurrently. # This option should be set only if `async_query_executor` option is set # to `:global_thread_pool`. #global_executor_concurrency: nil # Include the root model name in json serialization. (default: false) include_root_in_json: false # Include the _type field in serialization. (default: false) include_type_for_serialization: false # Whether to join nested persistence contexts for atomic operations # to parent contexts by default. (default: false) join_contexts: false # (Deprecated) When this flag is true, the attributes method on a document will return # a BSON::Document when that document is retrieved from the database, and # a Hash otherwise. When this flag is false, the attributes method will # always return a Hash. (default: false) #legacy_attributes: true # (Deprecated) Maintain legacy behavior of pluck and distinct, which does not demongoize # values on returning them. Setting this option to false will cause # pluck and distinct to return demongoized values. Setting this option to # false will also allow retrieving *_translations fields from pluck and # distinct and will return embedded values themselves (i.e. without # putting them in a hash). # (default: false) #legacy_pluck_distinct: true # When this flag is false, a document will become read-only only once the # #readonly! method is called, and an error will be raised on attempting # to save or update such documents, instead of just on delete. When this # flag is true, a document is only read-only if it has been projected # using #only or #without, and read-only documents will not be # deletable/destroyable, but will be savable/updatable. # When this feature flag is turned on, the read-only state will be reset on # reload, but when it is turned off, it won't be. # (default: false) #legacy_readonly: true # (Deprecated) Maintain legacy behavior of === on Mongoid document classes, which # returns true in a number of cases where Ruby's === implementation would # return false. Note that the behavior of === on Mongoid document # instances differs from both the behavior of === on document classes # and from Ruby's behavior of === on simple object instances regardless # of the value of this option. # (default: false) #legacy_triple_equals: true # Set the Mongoid and Ruby driver log levels when Mongoid is not using # Ruby on Rails logger instance. (default: :info) log_level: :info # When using the BigDecimal field type, store the value in the database # as a BSON::Decimal128 instead of a string. (default: true) #map_big_decimal_to_decimal128: true # (Deprecated) Force ``BSON::ObjectId#as_json`` method to return the hash # { "$oid" => id.to_s }. When this option is false, and bson-ruby 5 # is used, the return value will be the hexadecimal ObjectId string only. # (default: false) #object_id_as_json_oid: true # (Deprecated) When chaining the same operators that use the same field, setting this # feature flag to false will cause those operators to be combined using an # and. Setting this feature flag to true will cause the later chained # operators to overwrite the earlier ones. (default: false) #overwrite_chained_operators: false # Preload all models in development, needed when models use # inheritance. (default: false) preload_models: false # Raise an error when performing a #find and the document is not found. # (default: true) raise_not_found_error: true # Raise an error when defining a scope with the same name as an # existing method. (default: false) scope_overwrite_exception: false # (Deprecated) Use ActiveSupport's time zone in time operations instead of # the Ruby default time zone. See the time zone section below for # further information. (default: true) use_activesupport_time_zone: true # Return stored times as UTC. See the time zone section below for # further information. Most applications should not use this option. # (default: false) use_utc: false # (Deprecated) In MongoDB 4.0 and earlier, set whether to create # indexes in the background by default. (default: false) background_indexing: false # Configure driver-specific options. (optional) driver_options: # When this flag is turned off, inline options will be correctly # propagated to Mongoid and Driver finder methods. When this flag is turned # on those options will be ignored. For example, with this flag turned # off, Band.all.limit(1).count will take the limit into account, while # when this flag is turned on, that limit is ignored. The affected driver # methods are: aggregate, count, count_documents, distinct, and # estimated_document_count. The corresponding Mongoid methods are also # affected. (default: false, driver version: 2.18.0+) #broken_view_options: false # Validates that there are no atomic operators (those that start with $) # in the root of a replacement document, and that there are only atomic # operators at the root of an update document. If this feature flag is on, # an error will be raised on an invalid update or replacement document, # if not, a warning will be output to the logs. This flag does not affect # Mongoid as of 8.0, but will affect calls to driver update/replace # methods. (default: false, driver version: 2.18.0+) #validate_update_replace: false
버전 기반 기본값
Mongoid는 특정 버전의 구성 옵션을 기본값으로 설정하는 것을 지원합니다. 이는 새로운 Mongoid 버전으로 업그레이드할 때 유용합니다. Mongoid 버전을 업그레이드할 때 Mongoid::Config
에 다음을 설정해야 합니다.
Mongoid.configure do |config| config.load_defaults <OLD VERSION> end
이렇게 하면 새 버전의 Mongoid로 업그레이드할 때 코드가 이전 버전의 Mongoid의 구성 옵션으로 실행됩니다. 그런 다음 새 버전의 기능 플래그를 하나씩 변경하고 코드가 여전히 예상대로 작동하는지 테스트할 수 있습니다. 새 기능 플래그가 모두 확인되면 load_defaults
에 대한 호출을 새 버전을 사용하도록 변경하고 변경된 모든 기능 플래그를 제거할 수 있습니다. 예를 들어 7.5에서 8.0으로 업그레이드한다고 가정해 보겠습니다. 이 두 버전 사이에 legacy_attributes
및 map_big_decimal_to_decimal128
, 이렇게 두 가지 기능 플래그만 추가되었습니다. Mongoid 8로 업그레이드하기 전에 다음 줄을 추가할 수 있습니다.
Mongoid.configure do |config| config.load_defaults 7.5 end
이제 업그레이드 후 이 두 기능 플래그는 7.5 기능(legacy_attributes: true, map_big_decimal_to_decimal128: false
)으로 기본 설정됩니다. 이제 이러한 기능 플래그를 하나씩 설정하여 8.0 동작으로 전환할 수 있습니다:
Mongoid.configure do |config| config.load_defaults 7.5 config.legacy_attributes = false # config.map_big_decimal_to_decimal128 = true end
이 작업은 한 번에 하나씩 수행하는 것이 좋으므로 두 번째 플래그는 주석 처리해 두었습니다. legacy_attributes
플래그를 끈 상태에서 코드가 예상대로 작동하는지 확인한 후 map_big_decimal_to_decimal128
설정의 주석을 제거할 수 있습니다. 해당 기능이 확인되면 두 줄을 모두 제거할 수 있으며, load_defaults
를 다음으로 대체합니다:
Mongoid.configure do |config| config.load_defaults 8.0 end
ERb 전처리
구성 파일을 로드할 때 Mongoid는 이를 YAML로 구문 분석하기 전에 ERb로 처리합니다. 예를 들어, 이를 통해 환경 변수를 기반으로 런타임에 구성 파일의 내용을 구성할 수 있습니다.
development: clients: default: uri: "<%= ENV['MONGODB_URI'] %>"
참고
ERb에서 값을 출력할 때는 값이 유효한 YAML인지 확인하고 필요에 따라 이스케이프 처리하세요.
참고
ERb 렌더링은 YAML 구문 분석 전에 수행되므로 YAML 주석에 있는 지시어를 포함하여 구성 파일의 모든 ERb 지시어가 평가됩니다.
로깅
로깅을 구성할 때, Mongoid는 MongoDB Ruby 드라이버 위에 모델 레이어를 제공하고, 드라이버는 CRUD 작업을 MongoDB 배포에 할당한다는 점을 명심해야 합니다. 따라서 Mongoid를 사용하는 애플리케이션의 로깅 출력 중 일부는 Mongoid 자체에서 파생되고 일부는 드라이버에서 파생됩니다.
Mongo 클라이언트는 Ruby 드라이버 클라이언트 인스턴스이므로 Mongo 클라이언트의 로거(logger)는 Mongoid 로거가 아닌 Ruby 드라이버 로거입니다. 이를 다르게 설명하자면 다음과 같습니다:
# Ruby driver logger, not Mongoid logger Mongoid.client(:default).logger
Mongoid가 Ruby on Rails 애플리케이션에서 사용되는지 여부와 Mongoid와 Ruby 드라이버의 구성 방식에 따라 동일한 로거(logger) 인스턴스를 사용할 수도 있고 다른 인스턴스를 사용할 수도 있으며, 구성이 다를 수도 있습니다.
Ruby on Rails 애플리케이션
Ruby on Rails 애플리케이션에서 사용될 때 Mongoid는 기본적으로 Rails에서 로거와 로그 수준을 상속하고 드라이버의 로거를 동일한 로거 인스턴스로 설정합니다.
Rails.logger === Mongoid.logger # => true Mongoid.logger === Mongo::Logger.logger # => true
로그 수준을 변경하려면 표준 Rails 구성 을 사용합니다. . config/environments/production.rb
와 같은 환경 구성 파일 중 하나에 다음을 배치합니다.
Rails.application.configure do config.log_level = :debug end
참고
이 경우 Mongoid는 Rails의 로그 수준을 상속하므로 log_level
Mongoid 구성 옵션은 Mongoid가 Rails 애플리케이션에서 작동할 때는 사용되지 않습니다.
Mongoid 또는 드라이버 로거를 Rails 로거와 다르게 구성하려면 다음과 같이 이니셜라이저(initializer)를 사용합니다.
Rails.application.configure do config.after_initialize do # Change Mongoid log destination and/or level Mongoid.logger = Logger.new(STDERR).tap do |logger| logger.level = Logger::DEBUG end # Change driver log destination and/or level Mongo::Logger.logger = Logger.new(STDERR).tap do |logger| logger.level = Logger::DEBUG end end end
참고
현재 Ruby 표준 라이브러리 Logger
에는 로거가 사용하는 로그 장치(즉, IO
객체)를 반환하는 프로비저닝이 없습니다. 예를 들어, Mongoid 및/또는 Ruby 드라이버가 표준 Rails 로그 파일(예시: log/development.log
)에 로그를 기록하려면 표준 Rails 로거(Rails.logger
)와는 다른 수준으로 파일을 따로 열고 생성된 IO
객체를 Logger
생성자에 전달해야 합니다.
참고
기본적으로 Mongoid는 자체 로거와 드라이버 로거를 Rails 로거와 동일한 인스턴스로 설정하므로 인스턴스를 수정하면 모든 인스턴스에 영향을 미칩니다. 예를 들어 애플리케이션이 위에서 설명한 대로 Mongo::Logger.logger
에 별도의 Logger
인스턴스를 할당하지 않는 한 다음은 세 로거 모두에 대한 로그 수준을 변경합니다:
Mongoid::Logger.logger.level = Logger::DEBUG
독립형
Ruby on Rails 애플리케이션에 로드되지 않은 경우 Mongoid는 log_level
최상위 구성 옵션을 따릅니다. 구성 파일에서 다음과 같이 지정할 수 있습니다.
development: clients: default: # ... options: log_level: :debug
... 또는 Mongoid 인라인을 구성 시:
Mongoid.configure do |config| config.log_level = :debug end
Mongoid 7.1 이상의 기본 로그 대상은 표준 오류입니다. Mongoid 7.0 이하의 기본 로그 대상은 표준 출력입니다. 로그 대상을 변경하려면 다음과 같이 새 로거 인스턴스를 생성하세요.
Mongoid.logger = Logger.new(STDERR).tap do |logger| logger.level = Logger::DEBUG end
Ruby 드라이버 로그 수준 또는 대상을 변경하려면 다음을 수행하세요.
Mongo::Logger.logger = Logger.new(STDERR).tap do |logger| logger.level = Logger::DEBUG end
드라이버 로거를 Mongoid 로거와 동일하게 설정하려면 다음을 따릅니다:
Mongo::Logger.logger = Mongoid.logger
참고
Mongoid는 독립형 모드에서 실행할 때 드라이버의 로거를 변경하지 않습니다.
시간대
Ruby는 표준 라이브러리에서 시간대 지원이 제한되어 있습니다. ActiveSupport(Mongoid가 의존)는 보다 포괄적인 시간대 지원을 제공합니다. 참고로 Ruby와 ActiveSupport는 서로 다른 기본 시간대로 구성될 수 있습니다.
Ruby의 시간대와 관련한 상세 내용은 이 튜토리얼의 범위를 벗어나지만 올바른 시간대 처리를 달성하는 가장 쉽고 신뢰할 수 있는 방법은 다음과 같습니다.
운영 체제의 표준 시간대를 UTC로 설정합니다. 예를 들어 Linux의 경우:
cp /usr/share/zoneinfo/UTC /etc/localtime
ActiveSupport의 표준 시간대를 UTC로 설정합니다:
# If using Rails, in application.rb: class Application < Rails::Application config.time_zone = 'UTC' end # If not using Rails: Time.zone = 'UTC'
모든 시간을 UTC로 저장하고 유지합니다. 모든 시간 계산을 UTC 기준으로 수행합니다.
현지 시간으로 사용자 입력을 사용하여 작업할 때는 가능한 한 빨리 해당 사용자 입력을 UTC 시간으로 변환한 다음 UTC 시간으로 작업하세요.
시간을 렌더링하거나 다른 방식으로 표시할 때는 모든 계산을 수행한 후 실제로 렌더링할 때 해당 시간을 현지 시간으로 변환합니다.
날짜별 시간(예시: 특정 날짜가 시작하거나 끝나는 시간) 전환은 일반적으로 오류가 발생하기 쉽습니다. 이러한 변환 작업을 수행할 때는 보통 해당 시간이 사용될 시간대를 명시적으로 지정해야 합니다.
Mongoid를 사용하는 애플리케이션은 일반적으로 위에서 설명한 대로 ActiveSupport의 시간대를 구성한 다음 Time
이 아닌 Time.zone
을 사용하여(예시: Time.now
대신 Time.zone.now
) ActiveSupport 시간대 메커니즘을 호출해야 합니다. 이렇게 하면 개발 환경에서 흔히 볼 수 있는 것처럼 시스템 시간대가 UTC가 아닌 경우에도 올바른 결과를 얻을 수 있습니다.
MongoDB는 시간대 정보가 없으면 모든 시간을 UTC로 저장합니다.
Mongoid는 다음과 같은 시간대 관련 구성 옵션을 제공합니다.
use_activesupport_time_zone
: 이 옵션은 더 이상 사용되지 않으며 Mongoid 9.0에서 제거될 예정으로 항상 true로 동작합니다.true(기본값)인 경우
ActiveSupport::TimeWithZone
을 사용하여 시간 작업을 수행하는 것이 좋습니다.Time
유형의 필드에 있는 값은ActiveSupport::TimeWithZone
의 인스턴스로 반환됩니다. 시간대 정보 없이 시간을 구문 분석할 경우(예: 문자열이나 배열을 mongo 시스템에서 사용할 수 있도록 시간으로 변환하는 경우), 시간이 ActiveSupport의 시간대에 지정되어 있다고 가정합니다. 이는 기본 설정입니다.false인 경우 Ruby 표준 라이브러리
Time
클래스를 사용하여 시간 작업을 수행하는 것이 좋습니다.Time
유형의 필드에 있는 값은Time
인스턴스로 반환됩니다. 시간대 정보 없이 시간을 구문 분석하는 경우 시간이 Ruby 시간대에 지정되어 있다고 가정합니다.참고로
use_activesupport_time_zone
설정은 각각Date
및DateTime
클래스를 값으로 사용하는Date
또는DateTime
유형의 필드에는 영향을 주지 않습니다.또한 Mongoid는
use_activesupport_time_zone
설정과 상관없이 여전히 내부적으로Time
및ActiveSupport::TimeWithZone
클래스를 적절하게 활용할 수 있습니다.use_utc
: true면 MongoDB에 저장된 시간을 UTC로 반환합니다. false인 경우, MongoDB에 저장된 시간은 현지 시간으로 반환됩니다(use_activesupport_time_zone
설정 값에 따라 Ruby 기본 시간대 또는 ActiveSupport 시간대에서 각각Time
또는ActiveSupport::TimeWithZone
인스턴스로 반환). 기본값은 false입니다.use_utc
설정은 시간 구문 분석 방식에 영향을 주지 않으며, 구문 분석 중인 입력에 표준 시간대 정보가 포함되지 않은 경우 구문 분석은 항상 현지 시간으로 수행됩니다. UTC로 날짜를 구문 분석하려면 시스템/Ruby 또는 ActiveSupport 시간대를 UTC로 설정합니다(위에서 언급했듯이 세 가지를 모두 UTC로 설정하면 문제를 최소화할 수 있습니다).use_activesupport_time_zone
을 True로 설정하고Time.zone
을 UTC로 설정하는 것(또한 모든 시간 관련 작업에 ActiveSupport 시간 메커니즘 사용)을use_utc
를 True로 설장하는 것보다 더욱 권장합니다.
use_activesupport_time_zone
및 use_utc
옵션은 사용 가능한 시간대 정보를 버리지 않습니다. 예를 들어 Time 인스턴스에 연결된 시간대가 있는 경우, use_activesupport_time_zone
이 참일 때 ActiveSupport에서 구성한 시간대와 다르더라도 해당 시간대가 사용됩니다.
구성 SSLContext
예를 들어 특정 암호를 활성화하거나 비활성화하여 애플리케이션에서 TLS 옵션을 추가로 구성하는 것이 바람직할 수 있습니다.
Ruby 드라이버에서 TLS 컨텍스트 훅(hook)을 설정하여 이 작업을 수행할 수 있습니다. TLS 컨텍스트 훅은 소켓에서 사용하는 사용자 제공 Proc``s that will be invoked before any TLS socket
connection in the driver and can be used to modify the underlying
``OpenSSL::SSL::SSLContext
객체입니다.
TLS 컨텍스트 훅을 설정하려면 Proc``s to the ``Mongo.tls_context_hooks
배열을 추가합니다. 이 작업은 이니셜라이저(initializer)에서 수행할 수 있습니다. 아래 예시에서는 'AES256-SHA' 암호만 활성화하는 훅을 추가합니다.
Mongo.tls_context_hooks.push( Proc.new { |context| context.ciphers = ["AES256-SHA"] } ) # Only the AES256-SHA cipher will be enabled from this point forward
Proc
의 모든 Mongo.tls_context_hooks
은 OpenSSL::SSL::SSLContext
객체를 유일한 인수로 전달합니다. 이러한 프로세스는 소켓을 생성하는 동안 순차적으로 실행됩니다.
경고
TLS 컨텍스트 훅은 전역적이며 애플리케이션의 모든 Mongo::Client
인스턴스에 영향을 미칩니다.
TLS 컨텍스트 훅 할당 및 제거 권장 사항을 포함하여 TLS 컨텍스트 훅에 대한 자세한 내용은 Ruby 드라이버 설명서를 참조하세요.
클라이언트 측 암호화
구성 파일을 로드할 때, Mongoid는 다음 예시와 같이 클라이언트 사이드 암호화를 위한 스키마 맵에서 keyId
를 지정하는 데 사용되는 BSON::Binary
인스턴스를 파일에 포함할 수 있도록 허용합니다:
development: clients: default: database: blog_development hosts: [localhost:27017] options: auto_encryption_options: key_vault_namespace: 'keyvault.datakeys' kms_providers: local: key: "z7iYiYKLuYymEWtk4kfny1ESBwwFdA58qMqff96A8ghiOcIK75lJGPUIocku8LOFjQuEgeIP4xlln3s7r93FV9J5sAE7zg8U" schema_map: blog_development.comments: properties: message: encrypt: keyId: - !ruby/object:BSON::Binary data: !binary |- R/AgNcxASFiiJWKXqWGo5w== type: :uuid bsonType: "string" algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic" bsonType: "object"
포크 서버와 함께 사용
Puma, Unicorn 또는 Passenger와 같은 포킹(forking) 웹 서버와 함께 Mongoid를 사용하는 경우 포크 전에 상위 프로세스에서 Mongoid 모델에 대한 작업을 수행하지 않는 것이 좋습니다.
프로세스가 포크되면 Ruby 스레드가 하위 프로세스로 전송되지 않고 Ruby 드라이버 클라이언트 객체의 백그라운드 모니터링이 중단됩니다. 애플리케이션은 일반적으로 배포 상태가 변경될 때까지(예시: 네트워크 오류, 유지 관리 이벤트 등으로 인해) 정상적으로 작동하는 것처럼 보이지만, 이 시점에서 애플리케이션이 MongoDB 작업을 수행할 때 NoServerAvailable
예외가 발생하기 시작할 수 있습니다.
상위 프로세스가 MongoDB 데이터베이스에서 작업을 수행해야 하는 경우 포크 후 작업자의 모든 클라이언트를 재설정합니다. 이를 수행하는 방법은 사용 중인 웹 서버에 따라 다릅니다.
하위 프로세스를 포크한 후 상위 프로세스가 MongoDB 데이터베이스에서 작업을 수행할 필요가 없는 경우 하위 프로세스를 포크하기 전에 상위 프로세스의 클라이언트를 닫습니다. 상위 프로세스가 Mongo 클라이언트에서 작업을 수행하고 이를 닫지 않는 경우 상위 프로세스는 클러스터의 연결 슬롯을 계속 사용하며 상위 프로세스가 활성 상태인 한 클러스터를 계속 모니터링합니다.
참고
여기에 설명된 닫기/재연결 패턴은 Ruby 드라이버 버전 2.6.2 이상에서 사용해야 합니다. 이전 드라이버 버전에서는 다시 연결할 때 모니터링 스레드가 다시 생성되지 않았습니다.
Puma
on_worker_boot
훅을 사용하여 작업자의 클라이언트를 다시 연결하고 before_fork
훅을 사용하여 상위 프로세스의 클라이언트를 닫습니다(Puma 문서):
on_worker_boot do if defined?(Mongoid) Mongoid::Clients.clients.each do |name, client| client.close client.reconnect end else raise "Mongoid is not loaded. You may have forgotten to enable app preloading." end end before_fork do if defined?(Mongoid) Mongoid.disconnect_clients end end
유니콘
after_fork
훅을 사용하여 작업자에서 클라이언트를 다시 연결하고 before_fork
훅을 사용하여 상위 프로세스에서 클라이언트를 닫습니다(Unicorn 문서):
after_fork do |server, worker| if defined?(Mongoid) Mongoid::Clients.clients.each do |name, client| client.close client.reconnect end else raise "Mongoid is not loaded. You may have forgotten to enable app preloading." end end before_fork do |server, worker| if defined?(Mongoid) Mongoid.disconnect_clients end end
패신저
starting_worker_process
훅을 사용하여 작업자의 클라이언트를 다시 연결합니다(Passenger 문서). Passenger는 작업자가 포크되기 전에 상위 프로세스에서 호출되는 훅을 가지고 있지 않은 듯 보입니다.
if defined?(PhusionPassenger) PhusionPassenger.on_event(:starting_worker_process) do |forked| if forked Mongoid::Clients.clients.each do |name, client| client.close client.reconnect end end end end
쿼리 캐시 미들웨어
참고
Ruby 드라이버 버전 2.15 이상과 함께 사용하는 경우 Mongoid의 쿼리 캐시 미들웨어 는 드라이버의 쿼리 캐시 미들웨어에 위임됩니다.
Mongoid는 각 웹 요청 기간 동안 쿼리 캐시 를 활성화하는 Rack 미들웨어를 제공합니다. 다음은 Ruby on Rails 애플리케이션 에서 쿼리 캐시 미들웨어를 활성화 하는 방법의 예시 입니다.
# config/application.rb # Add Mongoid::QueryCache::Middleware at the bottom of the middleware stack # or before other middleware that queries MongoDB. config.middleware.use Mongoid::QueryCache::Middleware
Rails 애플리케이션에서 Rack 미들웨어를 사용하는 방법에 대한 자세한 내용은 Rails on Rack 가이드를 참조하세요.
개발 구성
드라이버의 기본 구성은 프로덕션 배포에 적합합니다. 개발 중에는 더 나은 개발자 환경을 제공하기 위해 일부 설정을 조정할 수 있습니다.
:server_selection_timeout
: MongoDB 서버가 로컬에서 실행 중이고 수동으로 시작하는 경우 이 값을 낮게(예:1
) 설정합니다. 서버 선택 시간 초과 값이 낮으면 실행 중인 서버가 없을 때 드라이버가 빠르게 실패하게 됩니다.
샘플 권장 개발 구성:
development: clients: default: database: mongoid hosts: - localhost:27017 options: server_selection_timeout: 1