2

我早就發現了早期的新手mongodb錯誤,並且在我應該嵌入它們時創建了很多has_many關係。mongoid將has_many關係轉換爲embeds_many

我的問題是我現在如何將我的記錄從一個多態has_many場景轉換爲embeds_many?

#Place.rb 
has_many :images, as: :imageable, dependent: :destroy, autosave: true 

#Image.rb 
belongs_to :imageable, polymorphic: true 

到=>

#Place.rb 
embeds_many :images, as: :imageable 

#Image.rb 
embedded_in :imageable, polymorphic: true 

我通常會遍歷通的所有記錄,這樣做的,但我想象中的命名會是一個問題。所以我不確定我如何才能完成創建臨時模型的這個短小,但是我希望其他一些人犯了同樣的錯誤,並且可能有一個溫和的解決方案?

回答

1

對於像我這樣的人,將來看到這個問題!

// Parent is parent model name without 's' and model is related model name without 's', 
// if you have something with plural name this function don't work 
// example : ref2em('user', 'post') 
var ref2em = function(parent, model) { 
    var query, update; 
    // Search through all instances 
    db[parent+'s'].find().forEach(function(ref) { 
    query = {}; 
    // Get all related models with parent_id 
    query[parent+"_id"] = ref._id; 
    db[model+'s'].find(query).forEach(function(em) { 
     // Update parent with $push operator (add model to parent's models attribute) 
     update = { $push: {} }; 
     update['$push'][model+'s'] = em; 
     db[parent+'s'].update({_id: ref._id}, update); 
    }); 
    }); 
} 

,然後使用這樣的(更新用戶的has_many:

您可以通過的has_many改變你的模型embeds_many(紅寶石基本代碼),然後使用這個JavaScript我寫了自己做的這帖子用戶embeds_many帖):

ref2em('user', 'post') 

(所有這些功能只是在蒙戈控制檯中工作,請確保您有一個備份,你知道你在做什麼,閱讀評論,我寫,並在年底降舊集合)。

沒有保修,我只是分享我所做的(可能不適合你)。