Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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 );
                });
         }
    );
});
like image 399
pretentiousgit Avatar asked Jul 08 '14 19:07

pretentiousgit


People also ask

How do I clone a document in MongoDB?

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.

What is a Mongoose 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.

What does lean () do Mongoose?

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.

What is _v in Mongoose?

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.


2 Answers

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(...);
like image 64
Richard Lovell Avatar answered Sep 22 '22 12:09

Richard Lovell


The answer is:

var s1 = new Session(session);
s1._id = undefined;
like image 21
pretentiousgit Avatar answered Sep 23 '22 12:09

pretentiousgit