Deep clone document with embedded associations

前端 未结 2 1398
后悔当初
后悔当初 2020-12-17 01:03

How would you go about deep cloning a document in MongoDB (mongoid)

I\'ve tried something like this;

original = Car.find(old_id)
@car = original.clon         


        
2条回答
  •  轮回少年
    2020-12-17 01:41

    You don't need to call .clone on this, you can use the raw data from attributes. For example the below method/example will give new ids throughout the entire document if it finds one.

    def reset_ids(attributes)
        attributes.each do |key, value|
            if key == "_id" and value.is_a?(BSON::ObjectId)
                attributes[key] = BSON::ObjectId.new
            elsif value.is_a?(Hash) or value.is_a?(Array)
                attributes[key] = reset_ids(value)
            end        
        end
        attributes
    end
    
    
    original = Car.find(old_id)
    car_copy = Car.new(reset_ids(original.attributes))
    

    And you now have a copy of Car. This is inefficient though as it has to go through the entire hash for the record to figure out if there are any embedded documents in an embedded document. You would be better off resetting the structure yourself if you know how it'll be, for example, if you have a parts embedded into car, then you can just do:

    original = Car.find(old_id)
    car_copy = Car.new(original.attributes)
    car_copy._id = BSON::ObjectId.new
    car_copy.parts.each {|p| p._id = BSON::ObjectId.new}
    

    Which is a lot more efficient than just doing a generic reset.

提交回复
热议问题