mongodb - Easiest way to copy/clone a mongoose document instance? -
my approach document instance, , create new 1 instance fields. sure there better way it.
can clarify mean "copy/clone"? going trying create duplicate document in database? or trying have 2 vars in program have duplicate data?
if 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 , y.name same x.name = "name_x"; y.name = "name_y"; console.log(x.name); // prints "name_x" console.log(y.name); // prints "name_y" }); }); in case, x , y 2 "copies" of same document within program.
alternatively, if wanted insert new copy of doc database (though different _id assume), this:
model.findbyid(yourid).exec( function(err, doc) { var d1 = doc; d1._id = /* set new _id here */; d1.save(callback); } ); or if you're doing outset, aka created document d1, can call save twice without setting _id:
var d1 = new model({ name: "john doe", age: 54 }); d1.save(callback); d1.save(callback); there 2 documents differing _id's , other fields identical in database.
does clarify things bit?
Comments
Post a Comment