How to remove attributes from the Mongoid model, that is, not just invalidate their values

I experimented with polymorphic association in Mongoid

class Group include Mongoid::Document belongs_to :groupable, polymorphic: true end class Album include Mongoid::Document has_many :groups, as: groupable end 

then I decided against it. So I deleted all lines belonging to belongs_to and has_many above. However, on the console, when I get the group entry I experimented with, it still has this attribute “groupable_type”. I know that remove_attribute resets the attribute, but does not remove it (sounds a bit like JavaScript). How can I remove this attribute from the database from Mongoid?

+6
source share
3 answers

You can do it:

 Group.collection.update({}, {'$unset' => {:groupable_type => 1}}, :multi => true) 
+13
source

Starting with version 5.0.0 of Mongoid, the pearl has switched from using Moped to using the "official ruby ​​MongoDB driver", which has a different syntax for updates. Link: https://docs.mongodb.org/ecosystem/drivers/ruby/

The documentation for the collection methods is here: http://api.mongodb.org/ruby/current/Mongo/Collection.html

There are two methods: "update" and "update_many". You can use update_many instead of specifying the "multi" option to update all documents.

Usage example for OPs case:

 Group.collection.update_many({}, {'$unset' => {'groupable_type' => true}}) 

Please note that you can delete embedded documents using dot notation:

 Group.collection.update_many({}, {'$unset' => {'embedded_doc.groupable_type' => true}}) 

Note that MongoDB is not supported to disable / update fields in an array. See this topic for information and workarounds: https://jira.mongodb.org/browse/SERVER-1243 .

+2
source

I noticed that in Moped 2.0.0.rc1 the update method is not in the collection, but it works;

 Group.collection.find().update( {'$unset' => {:groupable_type => 1}}, :multi => true) 
0
source

Source: https://habr.com/ru/post/907662/


All Articles