Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactiveMongoRepository not saving my data

I am noob in spring and mongo and noSQL.

I have connected to my mongoDB on local.

However my attempts to save my entity keeps failing.

val a0 = myEntity(name = "my Entity")
repository.save(a0)

My repository extends ReactiveMongoRepository<MyEntity, Long>.

But when I change it to extend MongoRepository<MyEntity, Long>, then it works.

What possibly could be the problem?

My database instance is running and working fine. I am guessing that it has to do something with reactive things.

like image 702
Kyoo Sik Lee Avatar asked Jul 17 '19 07:07

Kyoo Sik Lee


1 Answers

If you use reactive streams, you should be aware that nothing happens until you subscribe:

In Reactor, when you write a Publisher chain, data does not start pumping into it by default. Instead, you create an abstract description of your asynchronous process (which can help with reusability and composition).

By the act of subscribing, you tie the Publisher to a Subscriber, which triggers the flow of data in the whole chain. This is achieved internally by a single request signal from the Subscriber that is propagated upstream, all the way back to the source Publisher.

That means that if you use ReactiveMongoRepository, somewhere along the line you have to subscribe to your reactive stream. This can be done by using the subscribe() method on any Publisher. For example, using Java, that would be:

reactiveRepository
    .save(myEntity)
    .subscribe(result => log.info("Entity has been saved: {}", result));

Additionally, frameworks like Webflux will handle the subscription for you if you write reactive controllers. Using Java that means you could write something like:

@GetMapping
public Mono<MyEntity> save() {
    return reactiveRepository.save(myEntity); // subscribe() is done by the Webflux framework
}

Obviously, there's a lot more to reactive programming than just that, and you should be aware that you cannot simply swap MongoRepository to ReactiveMongoRepository without adapting to the reactive ecosystem and using reactive programming.

There's an Introduction to Reactive Programming chapter within the Reactor reference guide that might be interesting to read. The earlier quoted documentation also comes from this chapter of the reference guide.

like image 111
g00glen00b Avatar answered Sep 22 '22 01:09

g00glen00b