Is there a good pattern for copying database objects? To my understanding, you cannot edit the object id. So, if you copy an existing object to a newly created object, it will assume all properties of the existing object including the id. Since the id can’t be changed, is there a better way to copy an existing object?
Somewhat of an answer to my question. So, my approach was the following:
let copyObj = DB.object.create();
copyObj = existingObj;
This was giving me errors and was updating the existing object rather than copying and creating a new object. This is because copyObj
is being reinitialized as existingObj
. The work around is the following:
let copyObj = DB.object.create(existingObj);
This creates a new object with the contents of the existing object rather than overwriting the copyObj
variable to contain the contents of the existingObj
.
Please note that the relationships on the copyObj
need to managed separately.
Yes correct. copyObj
does NOT contain relationships to existingObj
. For instance, if existingObj
belongs to a User
object, copyObj
will not have that information from the solution code alone. One would then have to update the User of copyObj
.
You could also use the JavaScript method Object.assign if the second object was already created:
var one = DB.user.create();
one.name = "One";
one.save();
var two = DB.user.create();
Object.assign(two, one);
two.save();
console.log("One ", one);
console.log("Two ", two);
// One DatabaseObject{name: One}
// Two DatabaseObject{name: One}