Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove attributes from a Mongoid Model, i.e., not just nullifying their values

I was experimenting the polymorphic associaton 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 removed all those belongs_to and has_many lines above. Yet in the console, whenever I get a Group record that I experimented with, it still has this "groupable_type" attribute. I know remove_attribute nullify the attribute, but does not remove it( sounds a bit like JavaScript). How can I actually remove this attribute from the database from Mongoid?

like image 507
Nik So Avatar asked Feb 04 '12 20:02

Nik So


2 Answers

You could do this:

Group.collection.update({},
                        {'$unset' => {:groupable_type => 1}},
                        :multi => true)
like image 186
Sergio Tulentsev Avatar answered Sep 18 '22 06:09

Sergio Tulentsev


As of version 5.0.0 of Mongoid, the gem has switched from using Moped to use the 'official ruby MongoDB driver' which has a different syntax for updates. Reference: https://docs.mongodb.org/ecosystem/drivers/ruby/

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

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

Example use for the OPs case:

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

Note you can unset embedded documents using dot notation:

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

Note it is not well supported by MongoDB to unset / update fields within an array. See this thread for info and workarounds: https://jira.mongodb.org/browse/SERVER-1243.

like image 45
adailey Avatar answered Sep 21 '22 06:09

adailey