updating @DBref with spring data
<p>So We have a Collection with @DBRef list.</p>

<pre><code>/**
 * List of company users
 */
@DBRef
public List&lt;CompanyUser&gt; companyUsers = new ArrayList&lt;&gt;();
</code></pre>

<p>Spring Data very intelligently insert new entries into corresponding child collection and then update the parent collection with id references whenever we call <em>save</em> on a document.</p>

<p>What I am trying to do is to add a child element with update call, instead of fetching the whole document, adding an element and then calling save again.</p>

<p>It's not allowing me to do that, I guess it tries to add the child directly and figures out that it needs reference instead and hence provides error.</p>

<p>Other way is to make an entry into child collection and use that id as a reference id and call update.</p>

<p><strong>But is there a way to do it in a single call with spring data when I have a child element and id of the document?</strong></p>

<pre><code>public Company addUserToCompany(String id, CompanyUser companyUser) throws CimplyfiveException{
    Query query = new Query(new Criteria("_id").is(new ObjectId(id)));
    Update update = new Update().addToSet("companyUsers", companyUser);
    return modify(query, update, Company.class);
}
public &lt;T&gt; T modify(final Query query, final Update update, final Class&lt;T&gt; clazz){
        return geMongoTemplate().findAndModify(query, update, clazz);
}
</code></pre>

<p>Error :</p>

<pre><code>Cannot create a reference to an object with a NULL id.
</code></pre>

<p>P.S - I know @DBRef was a bad idea but it wasn't my idea and I wasn't there to cast my vote against it. :D</p>