RedEagle
RedEagle

Reputation: 4570

Mongo Spring Data "foreign" key

I'm using Spring Data to manage my MongoDB database.

On one collection I have 2 ObjectId fields, _id and one other that references an instance from another collection.

My collection's class is like:

public class CollectionA
{
private ObjectId id;
private String collectionADescription
private ObjectId collectionBId
}

with the class specified like this I am able to insert the "foreign key" sucessfully as an $oid.

The problem is that I am getting the following binding error:

Field error in object 'collectionA' on field 'collectionBId': rejected value []; codes [typeMismatch.collectionA.collectionBId,typeMismatch.collectionBId,typeMismatch.org.bson.types.ObjectId,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [collectionA.collectionBId,collectionBId]; arguments []; default message [collectionBId]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'org.bson.types.ObjectId' for property 'collectionBId'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.bson.types.ObjectId] for property 'collectionBId': no matching editors or conversion strategy found]

If I set the collectionBId variable to String the variables are inserted as string instead of $oid

How can I accomplish this?

Thans

Upvotes: 0

Views: 4429

Answers (1)

Ivan Sharamet
Ivan Sharamet

Reputation: 317

If you really want relations in your datastore, you should use Spring Data MongoDB @DBRef annotations. But I recommend you reconsider/redesign your schema in favor of using embedded documents. Maybe this document will help you to design better schema.

Upvotes: 2

Related Questions