Mongoid: convert embedded document to reference / own collection

I need to convert an embedded document into my own collection, so it can be referenced from another collection.

Suppose I have a Parent that inserts a lot of Childs . I thought about it:

 Parent.all.each do |p| p.childs.all.each do |c| c.raw_attributes['parent_id'] = p.id end p.save! #will save parent and cascade persist all childs onto their own coll end 

Is this an option? Ideally, I would run this in the console, and I would only change the mongoid mappings from embed_* to has_* , so I didn't need to change the rest of my code or use another collection as a stage.

+7
source share
3 answers

I think the code should look bigger (not tested)

 child_coll = Mongoid.database.collection('children') Parent.all.each do |p| p.childs.all.each do |c| c.attributes['parent_id'] = p.id child_coll.insert c.attributes # save children to separate collection end p.childs = nil # remove embedded data p.save end 

After that, you can change embeds_many to has_many and (hopefully) it should work well.

+9
source

too little rep for comments, but I think Sergio (otherwise very useful) the answer might be outdated. With mongoid 3.0.5 I could not use

child_coll = Mongoid.database.collection('children')

but used instead

child_coll = Mongoid.default_session[:children]

which helped

+6
source

For me, I need to remove the '_id' attribute before inserting, otherwise I will get a Duplicated key Error.

0
source

All Articles