mongodb 复制/克隆猫鼬文档实例的最简单方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18324843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Easiest way to copy/clone a mongoose document instance?
提问by fusio
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.
我的方法是获取文档实例,并从实例字段创建一个新实例。我相信有更好的方法来做到这一点。
采纳答案by Amalia
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 var
s in your program that have duplicate data?
你能澄清你所说的“复制/克隆”是什么意思吗?您是否要尝试在数据库中创建重复的文档?或者你只是想var
在你的程序中有两个具有重复数据的 s?
If you just do:
如果你只是这样做:
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"
});
});
In this case, x
and y
will be two "copies" of the same document within your program.
在这种情况下,x
并且y
将你的程序中的两个相同的文档的“副本”。
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:
或者,如果您想将文档的新副本插入数据库(尽管_id
我假设不同),则如下所示:
Model.findById(yourid).exec(
function(err, doc) {
var d1 = doc;
d1._id = /* set a new _id here */;
d1.save(callback);
}
);
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
:
或者,如果您从一开始就这样做,也就是您创建了一些 document d1
,您只需调用save
两次而无需设置_id
:
var d1 = new Model({ name: "John Doe", age: 54 });
d1.save(callback);
d1.save(callback);
There will now be two documents with differing _id
's and all other fields identical in your database.
现在将有两个文档具有不同的_id
's 并且您的数据库中的所有其他字段都相同。
Does this clarify things a bit?
这是否澄清了一些事情?
回答by jlchereau
The following code to clone documents in Amelia's response above does not work:
以下用于克隆上述 Amelia 响应中的文档的代码不起作用:
Model.findById(yourid).exec(
function(err, doc) {
var d1 = doc;
d1._id = /* set a new _id here */;
d1.save(callback);
}
);
You also need to reset
d1.isNew = true;
as in:
您还需要重置
d1.isNew = true;
为:
Model.findById(yourid).exec(
function(err, doc) {
doc._id = mongoose.Types.ObjectId();
doc.isNew = true; //<--------------------IMPORTANT
doc.save(callback);
}
);
回答by Asad Fida
The following code to clone documents:
以下代码克隆文档:
Model.findById(yourid).exec(
function(err, doc) {
var newdoc = new Model(doc);
newdoc ._id = mongoose.Types.ObjectId();
newdoc .save(callback);
}
);
回答by Espinasse
For simply clone use this :
对于简单的克隆使用这个:
Context.findOne({
_id: context._id
})
.then(function(c) {
c._id = undefined;
c.name = context.name;
c.address = context.address;
c.created = Date.now();
return Context.create(c.toObject());
}).then(function(c) {
return res.json({
success: true,
context: context
});
}).catch(function(err) {
next(err, req, res);
});
回答by Clayton Gulick
So, a lot of these answers will work well for simple docs, but there could be an error case when you're trying to make a deep clone of complex documents.
因此,很多这些答案对于简单的文档都适用,但是当您尝试对复杂文档进行深度克隆时,可能会出现错误情况。
If you have arrays of subdocs, for example, you can end up with duplicate _ids in your copied document, which can cause subtle bugs later.
例如,如果您有子文档数组,您可能会在复制的文档中得到重复的 _id,这可能会在以后导致细微的错误。
To do a deep clone of a mongoose doc, I suggest trying something like:
要对猫鼬文档进行深度克隆,我建议尝试以下操作:
//recursively remove _id fields
function cleanId(obj) {
if (Array.isArray(obj))
obj.forEach(cleanId);
else {
delete obj['_id'];
for (let key in obj)
if (typeof obj[key] == 'object')
cleanId(obj[key]);
}
}
let some_doc = await SomeModel.findOne({_id: some_id});
let new_doc_object = cleanId(some_doc.toObject());
let new_doc = new SomeModel(new_doc_object);
await new_doc.save();
This is going to be a pretty safe approach, and will ensure that every part of your object is cloned properly with newly generated _id fields on save.
这将是一种非常安全的方法,并将确保在保存时使用新生成的 _id 字段正确克隆对象的每个部分。