Is there a way to replace the original record with the new record, if the new record violates an unique key constraint using morphia in mongodb.
Upsert doesn't work for me as in morphia the object_id is null until it is saved into database and if the unique key constraint is generated because of another field it can't do upsert as the new record will have a different object_id then the original record.
I don't wanna lookup for the original record from db but just overwrite it if the new record creates an unique key constraint, is there a way to do this?
I think there are 3 possible approaches:
Fetch the ObjectId of the unique element, add it to the new document and save that. Since you are reusing the ObjectId, the old element will be overwritten. This requires two queries instead of one though.
Create an update query, where the query part checks for the unique attribute and explicitly set all attributes you want to change. This would work like this:
Query<User> updateQuery = datastore.createQuery(User.class)
.field("userId").equal("foo");
ops = datastore.createUpdateOperations(User.class).set("firstName", "bar");
datastore.update(updateQuery, ops);
Use your unique attribute as your ID via the @Id
annotation. However, there are some (minor) drawbacks: https://groups.google.com/forum/#!msg/morphia/GQLJywseiCM/6DVkYX17P68J
I would go with option 2.