Mongomapper:将文档复制到新文档中

时间:2011-03-09 06:04:52

标签: mongomapper

我有一个包含嵌入文档的mongomapper文档,并希望复制它。

从本质上讲,我想做的是这样的事情:

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

所以我想最终得到两个不同的mongomapper文档,但内容相同。

有任何想法应该如何做到这一点?

3 个答案:

答案 0 :(得分: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存储在新记录的某处,以便我可以跟踪谁来自谁,但这不是必需的。

答案 1 :(得分:4)

你应该能够做到这一点:

duplicate_doc = doc.clone
duplicate_doc.save

答案 2 :(得分: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

这在我的场景中实际上非常有效。但我很好奇人们是否有不同的解决方案。

相关问题