复制/克隆猫鼬文档实例的最简单方法? [英] Easiest way to copy/clone a mongoose document instance?

查看:68
本文介绍了复制/克隆猫鼬文档实例的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的方法是获取文档实例,并从实例字段中创建一个新实例.我相信有更好的方法来做到这一点.

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.

推荐答案

您能否阐明复制/克隆"的含义?您要尝试在数据库中创建重复的文档吗?还是您只是想在程序中有两个具有重复数据的var?

Can you clarify what you mean by "copy/clone"? Are you going trying to create a duplicate document in the database? Or are you just trying to have two vars in your program that have duplicate data?

如果您只是这样做:

Model.findById(yourid).exec(
    function(err, doc) { 
        var x = doc; 
        Model.findById(yourid).exec(
            function(err, doc2) {
                var y = doc2;
                // right now, x.name and y.name are the same
                x.name = "name_x";
                y.name = "name_y";
                console.log(x.name); // prints "name_x"
                console.log(y.name); // prints "name_y"
            }); 
    });

在这种情况下,xy将是程序中同一文档的两个副本".

In this case, x and y will be two "copies" of the same document within your program.

或者,如果您想将文档的新副本插入数据库(尽管我假设使用不同的_id),则将如下所示:

Alternatively, if you wanted to insert a new copy of the doc into the database (though with a different _id I assume), that would look like this:

Model.findById(yourid).exec(
    function(err, doc) {
        var d1 = doc;
        d1._id = /* set a new _id here */;
        d1.save(callback);
    }
);

或者,如果您从一开始就创建了d1文档,则只需调用两次save,而无需设置_id:

Or if you're doing this from the outset, aka you created some document d1, you can just call save twice without setting the _id:

var d1 = new Model({ name: "John Doe", age: 54 });
d1.save(callback);
d1.save(callback);

现在在数据库中将有两个文档具有不同的_id且所有其他字段都相同.

There will now be two documents with differing _id's and all other fields identical in your database.

这是否使事情澄清了?

这篇关于复制/克隆猫鼬文档实例的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆