Question

I have several mongo connections in my Rails app config. I need to take an User from database1 and save it into database2

Mongoid docs describe how to implement it http://mongoid.org/en/mongoid/docs/persistence.html#custom. But only for versions of mongoid 3+. I have 2.5.1 and cannot upgrade it.

User.with(database: 'staging') leads to undefined method `with' for User:Class (NoMethodError

Was it helpful?

Solution

I decided to use Moped for this task.

require 'moped'    

def connect_mongo(config)
  session = Moped::Session.new(["#{config['host']}:#{config['port']}"])
  session.use config['database']
  session.login config['username'],config['password']
  session
end

And the code of saving user to another DB:

mongo = connect_mongo(config1)
mongo_staging = connect_mongo(config2)

users = mongo[:users].find.limit(limit)
users.each do |user|
  # some code here ...
  mongo_staging[:users].insert(user)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top