Store functions in mongodb using Mongoid 3

As the name suggests. I can not find anything related to Mongoid 3. What I found applies only to older versions of mongoid that did not use Moped .

I found this and it does not 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 will add the getWeek function to the system.js collection.

How can this be done in mongoid 3?

+7
source share
1 answer

Nail!

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 use system.js in mongoid , as if it were a regular collection. I just add new documents.

IMPORTANT:

The value must be an instance of Moped::BSON::Code , otherwise it will be saved as a string, so it is useless. The identifier must be the name of the function. I was unable to specify the identifier in the create statement, so I added a few steps.

Just add this to your rake task to add all the necessary features to mongo after deployment.

+5
source

All Articles