title: Spring MongoDB manual reference
body: <p>I'm trying to create manual references in Spring MongoDB to simply store an ObjectId in reference field and populate it only if needed. (i.e. Without DBRef)</p>
  <p>However, I have not been able to find documentation on how to properly implement this.</p>
  <p>Suppose I have a simple model like this:</p>
  <pre class="lang-java prettyprint-override"><code>
  @Document(collection = &quot;person&quot;)
  public class Person{
  
      @Id
      private String id;
  
      ... other attributes
  
      //This is a reference to Address model
      private ObjectId address;
  
  }
  </code></pre>
  <p>And</p>
  <pre class="lang-java prettyprint-override"><code>@Document(collection = &quot;address&quot;)
  public class Address{
  
      @Id
      private String id;
  
      ... other attributes
  
  }
  </code></pre>
  <p>How can I create a manual reference here to only store the address model's ID in Person and then only populate when needed?</p>
  <p><strong>Update:</strong>
  To clarify, we already have a lot of documents on database that were previously inserted using Mongoose, where model A contains an ObjectId that references the model B. Using mongoose we were able to call <code>.populate</code> on these when needed. Then when we saved the document, Mongoose only saved the ObjectId.</p>
  <p>Basically I'm trying to implement a similar system in Spring.
  I created a custom converter that converts the ObjectId to the specific type when loading the data but this solution does not help since it does not convert the Model to ObjectId on save.</p>
  <p>Here is what we need:</p>
  <ol>
  <li>Reference field contains only an ObjectID or an array of IDs.</li>
  <li>We can populate the field only when needed.</li>
  <li>We can modify the populated field and call the save method, which updates both documents and only saves the ObjectId in the reference field.</li>
  <li>Reference field can be empty for some documents.</li>
  <li>When adding a new reference we can use either the ObjectID or the object. In either case, only ObjectID should be used.</li>
  </ol>
  <p>Again, this is exactly how Mongoose in Javascript works, which is what we are currently using.</p>
  <p>I'm looking either for a detailed answer or a some sort of tutorial that explains how this can be implemented since I have not been able to find any examples using manual reference which is very strange since manual reference is the more popular and recommended way of doing this.</p>