pixel
pixel

Reputation: 26441

ReactiveMongoTemplate findOne for non-existing element does not get called

I'm trying to obtain one document from collection. Document might not exist, and in case of null I wan to return default value.

My query and transformation:

    return template.findOne(Query().addCriteria(Criteria.where("id")), DeviceSettings::class.java)
            .map {
                when (it) {
                    null -> {
                        defaultSettings(clock)
                    }
                    else -> {
                        listOf(
                                Instant.now(clock).toString(),
                                it.nextMeasurement.toString(),
                                it.shouldUpdateFirmware.toString()
                        )
                    }
                }

            }
}

Unfortunately above map transformation does not get called.

When I simplify call to simple callable it gets called:

    return Mono.fromCallable({
        defaultSettings(clock)
    })

Upvotes: 0

Views: 2192

Answers (1)

adrian256
adrian256

Reputation: 46

Reactor does not use nulls in streams and fineOne should return empty mono when there is no result. In your case you should use switchIfEmpty operator

template.findOne(...) .map { listOf(...) } .switchIfEmpty(Mono.just(defaultSettings(clock))

Upvotes: 3

Related Questions