By default Mongomapper and Mongoid supports dynamic fields when you can store any value in MongoDB independently of the documentation schema. It can be really annoying when you’re working with many others and the software is getting bigger, since unknown fields can appear in the database which are used from one method but didn’t defined in model schema. Or just guess what happens when somebody makes a typo error and stores the first_name of the user to the fist_name attribute. Your mongo-mapper library won’t warn you about the error, just create the new wrong attribute and store it in the database.
I don’t like this kind of hidden information in the software because it just increases the complexity, so I was googling to find an option or something to turn this feature off. Mongoid has option to do this, but unfortunately in mongo-mapper it’s unsupported. So I forked down from mainline and created a patch on Github.
1 2 3 4 5 | class User include MongoMapper::Document self.forbid_dynamic_fields # self.allow_dynamic_fields = false end |
class User include MongoMapper::Document self.forbid_dynamic_fields # self.allow_dynamic_fields = false end
Now if you want to set an unknown field, the mongo-mapper will throw undefined method exception:
1 2 3 4 5 6 | user = User.new(:name => "Nucc") # => NoMethodError: undefined method `name=' for # user = User.new user.name = "Nucc" # => NoMethodError: undefined method `name=' for # |
user = User.new(:name => "Nucc") # => NoMethodError: undefined method `name=' for # user = User.new user.name = "Nucc" # => NoMethodError: undefined method `name=' for #
Leave Your Response