-
Let's say I have a function that takes a Document instance in parameter that may or may not have some populated paths. I'd like this function to always work a depopulated version of the document, so I could call How do I clone / deep copy a Document instance to do some work on it without side effects? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
There are a couple of possibilities that may work depending on your use case. Easiest way would be to just do The downside is that you lose change tracking, so |
Beta Was this translation helpful? Give feedback.
There are a couple of possibilities that may work depending on your use case.
Easiest way would be to just do
const clonedDoc = new MyModel(...doc.toObject())
orconst clonedDoc = MyModel.hydrate(doc.toObject())
, which gets you a new document with all the same properties asdoc
. You can then depopulate and do whatever you need to.The downside is that you lose change tracking, so
clonedDoc
wouldn't be aware of what paths indoc
are modified. But if you don't intend to doclonedDoc.save()
, this could work.