Mongomapper:将文档复制到新文档中
我有一个带有嵌入文档的 mongomapper 文档,并且想要复制它。
本质上,我想做的是这样的:
customer = Customer.find(params[:id])
new_customer = Customer.new
new_customer = customer
new_customer.save
所以我想最终得到两个不同的 mongomapper 文档,但内容相同。
有什么想法应该如何做到这一点?
I have a mongomapper document with embedded documents, and want to make a copy of it.
In essence, what I am trying to do is something like this:
customer = Customer.find(params[:id])
new_customer = Customer.new
new_customer = customer
new_customer.save
So I want to end up with two different mongomapper documents, but with identical content.
Any ideas how this should be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为此,您需要更改
_id
。具有相同_id
的文档被假定为同一文档,因此使用不同_id
保存文档将创建一个新文档。顺便说一句,我倾向于将旧的
_id
存储在新记录中的某个位置,以便我可以跟踪谁派生于谁,但这不是必要的。To accomplish this, you need to change the
_id
. Documents with the same_id
are assumed to be the same document so saving a document with a different_id
will create a new document.As an aside, I would be inclined to store the old
_id
somewhere in the new record so I could keep track of who derived from who, but it is not necessary.您应该能够简单地执行此操作:
You should simply be able to do this:
我认为不可能(或有效)在 mongodb/mongomapper 中创建现有文档的副本,因为在我看来,文档/嵌入文档及其原始文档和复制文档的 id 会发生冲突。
所以我通过将文档的内容复制到新文档中而不是文档本身来解决我的问题。这是一个示例:
这实际上在我的场景中效果很好。但我很好奇人们是否有不同的解决方案。
I don't think it is possible (or valid) to create copies of an existing document in mongodb/mongomapper because it seems to me that there would be a clash of the document/embedded documents and their ids of the original and copied documents.
So I solved my problem by copied the contents of the documents into new documents, rather than the documents themselves. Here is a sample:
This actually worked very well in my scenario. But I am curious if people have a different solution.