When you persisting a document using mongoTemplate.save() it destroys all unmapped fields in the database document.
For example, you have a collection "myDocument" with the document in the mongodb:
{
"_id": ObjectId("552402c3186eb112488b45ea"),
"field1": "value1",
"field2": "value2"
}
and your domain object looks like:
public class MyDocument {
@Id
private String id;
private String field1;
// getter and setter
}
after updating your document:
MyDocument doc = myDocumentRepository.getById(<some_id>);
doc.setField1("value3");
mongoTemplate.save(doc);
you will get the document in the collection without "field2":
{
"_id": ObjectId("552402c3186eb112488b45ea"),
"field1": "value3"
}
It looks like unexpected behaviour and may be a real stopper when few different applications are using the same database.
Is overriding of MongoTemplate method is acceptable workaround? Any other ideas will be very appreciated.
Thanks.
update
As noted by @helmy this is how mongoTemplate.save() works and usage of update methods is preferred. But in this case I'm loosing lifecycle events that built into mongodb mapping framework. For example, validation will not works on update as it triggered by listener in onBeforeSave event...
That's not unexpected or surprising at all, that's how save() works -- it overwrites the entire document.
I'd suggest that you take a look at the Spring Update class to perform your updates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With