Really hoping some of my mongodb/mongoose rude boyz and gangstas can help me out.
I need to clone a document in my mongodb, such that it's just a complete copy of the original. I've written a query to fetch the document back, which seems fine. I then took some node code I found online which strips out the id etc, and can insert it in my db correctly.
However.
The original document will have some subdocuments, and some related documents in other collections. They need to be copied too, and the id numbers stripped out and replaced (and the foreign key needs to be the new copied document, not the original). They're populated when I fetch the document, but I can't figure how to copy them as well.
Is there a way of doing this with a query? Or do I need to interrogate each collection in turn, seek out the foreign key, and copy each document in a forEach loop or something? This seems very complicated and inefficient (eg what if I add a new collection?)
Is there some kind of mongoose/mongo query, involving that '$unwind' and '$unset' business, maybe, where you can whip through several collections and pull out any documents with the correct foreign key, strip out their id, and copy them?
Thanks.
I need to clone a document in my mongodb, such that it's just a complete copy of the original. I've written a query to fetch the document back, which seems fine. I then took some node code I found online which strips out the id etc, and can insert it in my db correctly.
Code
copyDoc._doc._id = mongoose.Types.ObjectId()
copyDoc.name = 'Copy ' + copyDoc.name
copyDoc.isNew = true
const doc = await Model.create(copyDoc)However.
The original document will have some subdocuments, and some related documents in other collections. They need to be copied too, and the id numbers stripped out and replaced (and the foreign key needs to be the new copied document, not the original). They're populated when I fetch the document, but I can't figure how to copy them as well.
Is there a way of doing this with a query? Or do I need to interrogate each collection in turn, seek out the foreign key, and copy each document in a forEach loop or something? This seems very complicated and inefficient (eg what if I add a new collection?)
Is there some kind of mongoose/mongo query, involving that '$unwind' and '$unset' business, maybe, where you can whip through several collections and pull out any documents with the correct foreign key, strip out their id, and copy them?
Thanks.


