Mongoid: using more than one database?

2019-02-15 03:51发布

问题:

I'm using MongoDB and MongoID in a rails app, how can some models be a part of a different mongo database on the same server? How would I accomplish something like that? I've run into the same problem with mysql before and couldn't find a reasonable solution.

Any thoughts?

回答1:

The newest versions of Mongoid support this. See the docs.

Snippets:

config/mongoid.yml:

defaults: &defaults
  host: localhost
  slaves:
    - host: localhost
      port: 27018
    - host: localhost
      port: 27019
  databases:
    secondary:
      database: secondary_database
      host: localhost
      port: 27020
      slaves:
        - host: localhost
          port: 27021
        - host: localhost
          port: 27022

In your model:

class Business
  include Mongoid::Document
  set_database :secondary
end