How to clone a mongoose document?

夙愿已清 提交于 2021-02-08 17:12:31

问题


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

回答1:


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(...);



回答2:


The answer is:

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


来源:https://stackoverflow.com/questions/24640687/how-to-clone-a-mongoose-document

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!