'How to skip a document from retrieving in MongoRepository if it causes an error?

I'm working on a web application built using SpringBoot as backend and MongoDB as DBMS. I'm showing all the latest posts in a web page.

In the PostRepository.kt class, I'm retrieving all the latest posts.

@Aggregation(pipeline = [
    "{ \$match: { 'postName' : { \$exists: true } } }",
    "{ \$sort: { 'lastUpdateDate' : -1 } }",
    "{ \$limit : 10 }"
  ])
  fun getLatestPosts(): List<PostDocument?>

And the PostDocument.kt looks like this:

data class PostDocument(
  @Id
  val postId: String? = null,
  val postName: String? = null,
  val postedDate: LocalDate,
  val subPost: SubPostDocument,
  val lastUpdateDate: LocalDateTime,
  val postStatuses: PostStatus
) {
}

While reading from the DB, if, say, for example, subPost field is null, the webpage is breaking. So, I want to skip the posts for which some error happens while assigning them to PostDocument.

How can I do that?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source