pretentiousgit pretentiousgit - 1 year ago 282
Node.js Question

How to clone a mongoose document?

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.

function(err, session) {
var s1 = new Session();
s1 = session;
s1._id = undefined;

console.log('posting new test', s1._id); // your JSON {
if (err)

res.json( 'new session ', req.body );

Answer Source

The answer is:

var s1 = new Session(session);
s1._id = undefined;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download