如何在mongodb中连接2个不同的主机

时间:2019-03-19 19:34:30

标签: ruby mongodb mongoid

我有一个使用ruby的服务,并且尝试连接具有两个不同数据库的两个不同主机

我正在尝试类似的事情

mongoid.yml

development:
  clients:
    default:
      database: cpeTracking
      hosts:
       - development-shard.mongodb.net:27017
       - development-shard.mongodb.net:27017
       - development-shard.mongodb.net:27017
      options:
        user: my_user
        password: my_password
        auth_source: admin
        ssl: true
      database: testDb
        hosts:
        - localhost:27017

我的模特

class Movies
  include Mongoid::Document
  include Mongoid::Attributes::Dynamic
  store_in database: "testDb"

  field :name, type: String
  field :year, type: Integer
  field :director, type: String
end

运行服务时,仅与第一台主机连接。 我也尝试过这种解决方案 Connecting to two databases Mongoid但不起作用

1 个答案:

答案 0 :(得分:0)

我找到了答案。 首先,我必须创建一个默认级别相同的新客户端,我将其与数据库和主机的信息称为“辅助”。

development:
  clients:
    default:
      database: my_db
      hosts:
        - development-shard.mongodb.net:27017
        - development-shard.mongodb.net:27017
        - development-shard.mongodb.net:27017
      options:
        user: my_user
        password: my_pass
        auth_source: admin
        ssl: true
    secondary:
      database: testDb
      hosts:
       - localhost:27017

第二。在模型中,我必须添加将使用

的集合,数据库和客户端
class Movies
  include Mongoid::Document
  include Mongoid::Attributes::Dynamic
  store_in collection: "movies", database: "testDb", client: "secondary"

  field :name, type: String
  field :year, type: Integer
  field :director, type: String
end