I am using the mongoDb with Micronaut and trying to insert, get, delete and update the record. I have followed the guideline from here https://github.com/ilopmar/micronaut-mongo-reactive-sample
Since I don't have a database created in the MongoDB,
Micronaut configuration
mongodb:
uri: "mongodb://${MONGO_HOST:localhost}:${MONGO_PORT:27017/FeteBird-Product}"
Repository
@Singleton
public class Repository<T> implements IRepository<T>{
private final MongoClient mongoClient;
public Repository(MongoClient mongoClient) {
this.mongoClient = mongoClient;
}
@Override
public MongoCollection<T> getCollection(String collectionName, Class<T> typeParameterClass) {
return mongoClient
.getDatabase("FeteBird-Product")
.getCollection(collectionName, typeParameterClass);
}
}
Insert operation
public Flowable<List<Product>> findByFreeText(String text) {
LOG.info(String.format("Listener --> Listening value = %s", text));
try {
Product product = new Product();
product.setDescription("This is the test description");
product.setName("This is the test name");
product.setPrice(100);
product.setId(UUID.randomUUID().toString());
Single.fromPublisher(this.repository.getCollection("product", Product.class).insertOne(product))
.map(item -> product);
} catch (Exception ex) {
System.out.println(ex);
}
return Flowable.just(List.of(new Product()));
}
There is no record inserted or created an database, What I am doing wrong ?
Yes, nothing is created, because you are using reactive Single
without subscription. And then it is never executed. So, you have to call subscribe()
to tell the Single
that it can start working:
Single.fromPublisher(repository.getCollection("product", Product.class).insertOne(product))
.subscribe();
Note: the mapping of item to product .map(item -> product)
is unnecessary when you don't use the result of the subscription.
There is no subscription in the linked example for the first look, because the controller method returns Single<User>
and then the subscriber in that case is the REST operation caller.