Template for updating objects / documents with Spring-Data MongoDB and Spring MVC

I am trying to create a reusable pattern for updating MongoDB documents when using Spring data in combination with Spring MVC.

A usage example can be summarized as follows:

  • Document is generated in Mongo using repository.save ()
  • Portions of this document are then presented in editable Spring MVC form.
  • The user submits updated portions of this document, which are then saved.

If I use the repository.save () method in step 3, I lose any data in the document that is not bound to the form. Making a form that is responsible for the entire document is fragile, so here it seems like the findAndModify () method for MongoTemplate will come in handy.

To use the findAndModify () method, I created Form objects that support the toMap () method, which takes the properties of the Form object as a Map and removes some of the fields (such as class and id). This gives me a map that only contains the fields I care about from the Form object. By passing the object id and this map to the update () method in my custom repository, I create Query and Update objects that I can pass to the findAndModify () method.

Using this approach, I can easily add fields to my objects and only worry about cases where there are fields that I don't want to update from posting the form. Document fields that are not processed by the form must be preserved. It still seems a bit confusing to use both the repository and the MongoTemplate, so I'm wondering if there are better examples on how to handle this. It looks like it should be a consistent model when working with Mongo and Spring MVC (at least).

I've created a sample project showing how I can achieve this model on GitHub. Spock's tests show how "updating" the document using save () will reset the fields as expected and my update () method.

https://github.com/watchwithmike/diner-data

What do other people do when doing partial document updates using Spring MVC and Spring Data?

+3


source to share


1 answer


If you take what the user provides and just push it into the database, you run the risk of doing something dangerous, like updating or creating data that they cannot. Instead, you must first query Mongo to get the most recent version of the document, change any fields (it looks like you are using Groovy so you can loop through all the properties and set them in a new document), and then save a new, complete document.



If you are doing small incremental updates (like increasing votes or something), you can create a custom MongoDB query with MongoTemplate

to update multiple fields. See the spring-data-mongodb

docs for details . You can also add custom methods to MongoRepository

those that use MongoTemplate

.

0


source







All Articles