This is a followup to Easiest way to copy/clone a mongoose document instance?, which isn't working for me.
The following code throws a "cannot edit Mongo _id" field, rather than wiping the ._id and creating a new document in the collection.
Is there a better way to clone all values of a document into a new document, for further use/testing/etc?
I'm on Mongoose 3.8.12/Express 4.0, and I have also tested this on creating a new ObjectID in the 'undefined' s1._id field below.
router.route('/:sessionId/test/:testId')
.post(function(req,res){
Session.findById(req.params.sessionId).exec(
function(err, session) {
var s1 = new Session();
s1 = session;
s1._id = undefined;
console.log('posting new test', s1._id); // your JSON
s1.save(function(err) {
if (err)
res.send(err);
res.json( 'new session ', req.body );
});
}
);
});
To clone a document, hover over the desired document and click the Clone button. When you click the Clone button, Compass opens the document insertion dialog with the same schema and values as the cloned document. You can edit any of these fields and values before you insert the new document.
In Mongoose, a "document" generally means an instance of a model. You should not have to create an instance of the Document class without going through a model.
The lean option tells Mongoose to skip hydrating the result documents. This makes queries faster and less memory intensive, but the result documents are plain old JavaScript objects (POJOs), not Mongoose documents.
In Mongoose the “_v” field is the versionKey is a property set on each document when first created by Mongoose. This is a document inserted through the mongo shell in a collection and this key-value contains the internal revision of the document.24-Jun-2021.
You need to create a new id for the document you want to clone and set isNew to true, so given "session" is the document you want to clone:
session._doc._id = mongoose.Types.ObjectId();
session.isNew = true;
session.save(...);
The answer is:
var s1 = new Session(session);
s1._id = undefined;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With