5

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 );
                });
         }
    );
});
Community
  • 1
  • 1
pretentiousgit
  • 165
  • 2
  • 9
  • 1
    Thanks for coming back and proving the answer. However you should add this as an answer yourself (and accept it) rather than editing the question. – Don Cruickshank Jul 08 '14 at 20:17

2 Answers2

8

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(...);
Richard Lovell
  • 848
  • 10
  • 18
7

The answer is:

var s1 = new Session(session);
s1._id = undefined;
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
pretentiousgit
  • 165
  • 2
  • 9
  • You can't save a document without an _id, how can this even work? See http://stackoverflow.com/questions/25345274/mongoose-data-saving-without-id – Nepoxx Feb 25 '15 at 21:42
  • This method initialises empty arrays if you have defined any arrays in schema. – Ivan Wang Oct 19 '15 at 23:41