Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to copy/clone a mongoose document instance?

My approach would be to get the document instance, and create a new one from the instance fields. I am sure there is a better way to do it.

like image 763
fusio Avatar asked Aug 31 '25 15:08

fusio


1 Answers

You need to reset d1.isNew = true; as in:

Model.findById(yourid).exec(
    function(err, doc) {
        doc._id = new mongoose.Types.ObjectId();
        doc.isNew = true; //<--------------------IMPORTANT
        doc.save(callback);
    }
);

                
                                                                                                                                                                                                                        
like image 176
jlchereau Avatar answered Sep 10 '25 19:09

jlchereau