Hello,
I recently started working with mongodb and java for a project. Although I managed to connect mongodb and apply all kind of operations (find, insert, delete, update) successfully, I encountered a very strange problem:
I use three classes: EventDao class, MongoDB class and EventDaoTest class. A brief description of the classes:
- MongoDB class connects with mongoDB and inserts a doc. Example of code:
public void insert(String record) {
try (MongoClient mongoClient = MongoClients.create(uri)) {
System.out.println(record);
this.database = mongoClient.getDatabase("tg-db");
this.collection = this.database.getCollection(this.collectionName);
Document doc = Document.parse(record);
this.collection.insertOne(doc);
}
}
- EventDao class uses the insert function from MongoDB class to insert an Event object into the database. Example of code:
public void insert(Event event) {
this.mongoDB.insert(this.gson.toJson(event));
}
- EventDaoTest class contains a main for testing reasons (test the insert function). Example of code:
public static void main(String[] args) {
EventDao eventDao = EventDao.getInstance();
Event event = new Event("e101", "testing");
eventDao.insert(event);
}
Notes
As I have mentioned, I managed to connect to mongoDB by creating a main function in MongoDB class. The problem seems to be when I create from the EventDao class a MongoDB instance and Im trying to insert a record. I am always getting a createTimeoutException. Also, it is worth mentioning that I created a main function in MongoDB class, created an EventDao instance and it worked. So, I concluded that the main problem is when Im trying to invoke a function in MongoDB class from another class (here this is the EventDao class).
Does anyone know what goes so wrong? I have been struggling for hours.