How to clone a mongoose document?

mongoose, node.js

Solution

The answer is:

var s1 = new Session(session);
s1._id = undefined;

Problem

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 ); }); } ); }); ```

Original source

Related problems