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)
However, I have not been able to find documentation on how to properly implement this.
Suppose I have a simple model like this:
@Document(collection = "person")
public class Person{
@Id
private String id;
... other attributes
//This is a reference to Address model
private ObjectId address;
}
And
@Document(collection = "address")
public class Address{
@Id
private String id;
... other attributes
}
How can I create a manual reference here to only store the address model's ID in Person and then only populate when needed?
Update:
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 .populate on these when needed. Then when we saved the document, Mongoose only saved the ObjectId.
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.
Here is what we need:
- Reference field contains only an ObjectID or an array of IDs.
- We can populate the field only when needed.
- We can modify the populated field and call the save method, which updates both documents and only saves the ObjectId in the reference field.
- Reference field can be empty for some documents.
- When adding a new reference we can use either the ObjectID or the object. In either case, only ObjectID should be used.
Again, this is exactly how Mongoose in Javascript works, which is what we are currently using.
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.