2011-03-09 67 views
5

我有一个嵌入文档的mongomapper文档,并且希望复制它。Mongomapper:将文档复制到新文档中

从本质上讲,我试图做的是这样的:

customer = Customer.find(params[:id]) 
new_customer = Customer.new 
new_customer = customer 
new_customer.save 

所以我想有两个不同的mongomapper文件结束,但相同的内容。

任何想法如何做到这一点?

+0

从一个小阅读中,我已经做了,我在父文档中嵌入文档的身影做到这一点的唯一方法是进行循环,得到他们的属性,通过为每个属性复制这些属性来创建新文档,直到我拥有该文档的副本。任何人都可以想到另一种方式? – futureshocked

回答

4

要完成此操作,您需要更改_id。具有相同_id的文档被假定为相同的文档,因此保存具有不同_id的文档将创建新文档。

customer = Customer.find(params[:id]) 
customer._id = BSON::ObjectId.new # Change _id to make a new record 
    # NOTE: customer will now persist as a new document like the new_document 
    # described in the question. 
customer.save # Save the new object 

顺便说一句,我会倾向于在一些地方保存旧_id在新的记录,所以我可以跟踪谁从谁得到的,但它是没有必要的。

+0

不错,我可以看到我可以如何将您创建的新ID与我处理嵌入文档的方式相结合,即为文档及其嵌入文档的新副本添加新的ID。 – futureshocked

0

我不认为有可能(或有效)在mongodb/mongomapper中创建现有文档的副本,因为在我看来,文档/嵌入文档及其原始文档的ID会发生冲突并复制文件。

因此,我通过将文档内容复制到新文档而不是文档本身来解决了我的问题。这里是一个样本:

inspection = Inspection.find(params[:inspection_id]) #old document 
new_inspection = Inspection.create     #new target document 
items = inspection.items        #get the embedded documents from inspection 

items.each do |item|         #iterate through embedded documents 
    new_item = Item.create       #create a new embedded document in which 
                 # to copy the contents of the old embedded document 
    new_item.area_comment = item.area_comment   #Copy contents of old doc into new doc 
    new_item.area_name = item.area_name 
    new_item.area_status = item.area_status 
    new_item.clean = item.clean 
    new_item.save          #Save new document, it now has the data of the original 
    new_inspection.items << new_item     #Embed the new document into its parent 
    end 

new_inspection.save         #Save the new document, its data are a copy of the data in the original document 

这实际上在我的情况下工作得很好。但我很好奇,如果人们有不同的解决方案。

4

你应该仅仅是能够做到这一点:

duplicate_doc = doc.clone 
duplicate_doc.save 
相关问题