Spring Data Mongo with Koltin coroutines and @DocumentReference

Viewed 25

I am using Spring Data MongoDB with Kotlin Coroutines to create a non-blocking server. I have a document Deck:

@Document 
data class Deck(
@Id val id: ObjectId = ObjectId.get(),
@DocumentReference(lazy = true) val author: User,
val title: String,
val desc: String,
@DocumentReference(lazy = true) val cards : Set<Card> = emptySet(),
@CreatedDate val createdAt: Instant = Instant.now(),
@LastModifiedDate val lastModifiedAt: Instant = Instant.now()
)

Deck has a reference to a User type in the author field:

@Document
data class User(
@Id val id: ObjectId = ObjectId.get(),
val name: String,
@Indexed(unique = true, name = "username_index") val username: String,
val password: String,
@CreatedDate val createdAt: Instant = Instant.now(),
@LastModifiedDate val lastModifiedAt: Instant = Instant.now(),
@DocumentReference(lazy = true) val decks: Set<Deck> = emptySet()
)

Here's my DeckRepository interface:

interface DeckRepository: CoroutineSortingRepository<Deck, String> {
}

The Deck documents are getting saved properly in the database with the author's ObjectId. But when I try to fetch the deck with id, the repository method gives an error. It's not able to populate the author's reference.

override suspend fun getDeck(deckId: String): DeckResponseDTO {
    log.info("Getting deck with id $deckId")
    return deckRepository.findById(deckId)?.toDto() ?: throw Exception("Could not find deck with id $deckId")
    }

Stacktrace snippets:

Failed to instantiate io.gitub.startswithzed.dex.model.Deck using constructor fun <init>(org.bson.types.ObjectId, io.gitub.startswithzed.dex.model.User, kotlin.String, kotlin.String, kotlin.collections.Set<io.gitub.startswithzed.dex.model.Card>, java.time.Instant, java.time.Instant): io.gitub.startswithzed.dex.model.Deck with arguments 63173407712ec0263535829a,null,Test title,Test Desc,null,2022-09-06T11:50:31.370Z,2022-09-06T11:50:31.370Z,16,null
at org.springframework.data.mapping.model.KotlinClassGeneratingEntityInstantiator$DefaultingKotlinClassInstantiatorAdapter.createInstance(KotlinClassGeneratingEntityInstantiator.java:215) ~[spring-data-commons-2.7.2.jar:2.7.2]

Caused by: java.lang.NullPointerException: Parameter specified as non-null is null: method io.gitub.startswithzed.dex.model.Deck.<init>, parameter author
at io.gitub.startswithzed.dex.model.Deck.<init>(Deck.kt) ~[main/:na]
at io.gitub.startswithzed.dex.model.Deck.<init>(Deck.kt:14) ~[main/:na]

I even verified the data by querying using lookup in the console. Somehow Spring Data is not able to query properly.

Thanks for the help!

0 Answers
Related