Mongo @DBRef unique

1.5k views Asked by At

My application uses Spring Boot / JPA / MongoDB.

I map my domain classes to MongoDB using

org.springframework.data.mongodb.core.mapping.Document;
org.springframework.data.mongodb.core.index.Indexed;
org.springframework.data.mongodb.core.mapping.DBRef;

All is well except when trying to make a DBRef unique :

@DBRef @Indexed(unique = true)
private User owner;

I have tried different combinations of @DBRef, @Indexed (unique=true) and cannot make the DBRef unique. I can make other field-types unique, such as 'name' in the following example

@Indexed(unique = true)
@Size(min = 2, max = 100)
@Column(length = 100)
private String name;

but cannot find how to make my DBRef field unique.

1

There are 1 answers

3
xeraa On

I'm coming from the Morphia side of mapping, but I'd try this:

@CompoundIndexes({
    @CompoundIndex(name = "owner", def = "{'owner.id' : 1}", unique = true)
})