Search code examples
ruby-on-railsmongoid3

Store functions in mongodb using Mongoid 3


Just as the title suggests. I am not able to find anything related to Mongoid 3. The things I found only apply to old versions of mongoid that didn't use Moped.

I found this and it doesn't work:

def self.install_javascript
  getWeekJs = Rails.root.join("lib/javascript/getWeek.js")
  if collection.master['system.js'].find_one({'_id' => "getWeek"}).nil?
    collection.master.db.add_stored_function("getWeek", File.new(getWeekJs).read)
  end
end

This method would add a getWeek function to the system.js collection.

How can this be done in mongoid 3?


Solution

  • Nailed it!

    Codes:

    class StoredProcedure
      include Mongoid::Document
      store_in collection: "system.js"
    
      field :_id, type: String, default: ""
    
      def self.test
        equalsJS = Rails.root.join("lib/assets/javascripts/equals.js")
        code = Moped::BSON::Code.new(File.new(equalsJS).read)
        unless where(id: "equals").first
          proc = new(value: code)
          proc._id = "equals"
          proc.save
        end
      end
    end
    

    Explanation:

    I'm using the system.js in mongoid as if it were a normal collection. I'm then simply adding new documents.

    IMPORTANT:

    The value needs to be a Moped::BSON::Code instance otherwise it will be saved as string, thus useless. The id needs to be the function's name. I wasn't able to specify the id in a create statement, therefore I added multiple steps.

    Just add this to a rake task to make sure you add all required functions to mongo after deployment.