Mongoid:将嵌入式文档转换为引用/自己的集合

Mig*_*ing 8 ruby migration mongodb mongoid

我需要将嵌入的文档转换为自己的集合,因此可以从另一个集合中引用它.

让我们假设我有一个Parent嵌入很多Childs.我在考虑这个问题:

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
Run Code Online (Sandbox Code Playgroud)

这是一个选择吗?理想情况下,我会在控制台中运行它,我只会将mongoid映射更改embed_*has_*,所以我不需要更改我的其余代码或使用另一个集合作为暂存.

Ser*_*sev 10

我认为,代码看起来应该更像这样(没有测试)

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
Run Code Online (Sandbox Code Playgroud)

在那之后,你可以改变你的embeds_many,has_many并且(希望)它应该运作良好.


sba*_*uch 6

很少有人评论,但我认为塞尔吉奥(否则非常有帮助)的答案可能已经过时了.使用mongoid 3.0.5我无法使用

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

而是使用

child_coll = Mongoid.default_session[:children]

这对我有用