How to programmatically get the current database Mongoid is writing to?

前端 未结 5 1676
南笙
南笙 2021-02-13 15:22

I am talking to multiple databases using Mongoid.override_database(\"database_name\") using Mongoid with rails. How do I find the current database programmatically?

Mon

相关标签:
5条回答
  • 2021-02-13 16:04

    Got it!

    Mongoid.default_session.options[:database]
    
    0 讨论(0)
  • 2021-02-13 16:07

    Running Mongoid.default_session.options[:database] gives an error that default_session is invalid. It is now default_client. That works wonderfully.

    Run it without the [:database] to get all the option and see the full configuration of your database.

    Mongoid::Config.clients["default"]["database"] assumes you are NOT using the uri version of mongoid.yml. You will get nil in all cases. Use Mongoid::Config.clients["default"] to get the full configuration of the current database, or Mongoid::Config.clients["default"]['uri'] to give you just the full uri.

    Pick the database name from the URI after the last port number/. There could be severalif using a sharded configuration

    0 讨论(0)
  • 2021-02-13 16:10

    Mongoid Version 7.0.5

    Mongoid.client(:default).database
    
    0 讨论(0)
  • 2021-02-13 16:14

    If you want the overrided database you actually need to use

    Mongoid::Threaded.database_override
    
    0 讨论(0)
  • 2021-02-13 16:16

    The new way to get this is

    Mongoid::Config.clients["default"]["database"]
    

    You can also just have a look at

    Mongoid::Config.clients
    

    to see what else is available.

    0 讨论(0)
提交回复
热议问题