mongo_orm custom name for collection
mongo_orm will automatically determine the name for your collection by using the Module and Class name, and appending an “s”.
In cases where you want to name your collection, you can simply do this:
class PapiTest < Mongo::ORM::Document
collection_name “Buster”
field test : String
endget “/” do
pt = PapiTest.new
pt.test = “I want your sex”
pt.save!
“Hello World!”
endKemal.run
In my example, the collection will be called Buster.
Internally, this is realized by a macro which looks like this:
# specify the collection name to use otherwise it will use the model’s name
macro collection_name(name)
{% SETTINGS[:collection_name] = name.id %}
end
It’s important to understand, that the development is done in the context of a macro here! Therefore .id is NOT a class variable/ method you have to pass in, but a special function in the macro context which will return a MacroID for the string’s content.
Refer to this documentation: https://crystal-lang.org/api/0.27.2/Crystal/Macros/MacroId.html
belongs_to is realized in a similar fashion. It allows you to create relationships between Documents / Collections.
belongs_to :user, class_name: FictitiousModule::FictiticiousClass
is realized internally as a macro:
macro belongs_to(model_name, class_name=nil)
field {{class_name ? class_name.id.underscore.gsub(/::/,”_”) : model_name.id}}_id : BSON::ObjectId
(…)
here class_name: in the original macro call refers to the second variable which is nil by default. The macro checks whether it is not nil, and chooses what to use.