Search code examples
mongodbscalamongo-scala-driver

mongo-scala-driver does not insert


I have approximately this database wrapper class:

    class MyDatabase {
             private def getMongoClientSettings(): MongoClientSettings = {
               val uri = "mongodb://localhost:27017"
               val mongoClientSettings = MongoClientSettings.builder().applyConnectionString(ConnectionString(uri))
                        .serverApi(ServerApi.builder().version(ServerApiVersion.V1).build())
                        .build()
              mongoClientSettings
            }
            private val mongoClient = MongoClient(getMongoClientSettings)
            private val db = mongoClient.getDatabase("myDatabase")
        
            object groups {
               val collection = db.getCollection("groups")
               ...
            }
            object posts {
               val collection = db.getCollection("posts")
               ...
            }
            object likes {
              val collection = db.getCollection("likes")
            ...
           }
}

The problem is that some inserts succeed, while other inserts silently fail.

For example, in the groups object, this command succeed:

  val doc = Document("_id" -> group.id, "name" -> group.name, "screenName" -> group.screenName,
    "membersCount" -> group.membersCount, "lastInspectionDate" -> group.lastInspectionDate)
  collection.insertOne(doc)

But, in the posts object, the inserts never succeed (here, the id field is not the primary key, the _id key is to be autogenerated and is not the same as id):

val doc = Document("id" -> post.id, "fromId" -> post.fromId, "ownerId" -> post.ownerId,
"publishDate" -> post.publishDate, "text" -> post.text, "isPinned" -> post.isPinned)
collection.insertOne(doc)

The question is: why for the posts collection, the inserts never succeed?

My thoughts:

  1. maybe db.getCollection command somewhat disconfigures the other collections, and I would need to call db.getCollection right before the insertOne command? This is unrealistic.
  2. I thought that the method exited before the insertOne succeed, but for the groups collection, there is no problem.
  3. I tried to perform waiting using this command, still no posts inserted: Await.result(collection.insertOne(doc).toFuture, Duration.Inf)
  4. I found some mentions about the need to "subscribe" to the observable to make the cold steam to start functioning, but I think this was relevant for older versions only.

Configuration: Linux Ubuntu 18.04, Scala 2.12.14, Mongo-Scala-Driver 4.3.1, MongoDB 5.0.2.

Looking forward to your replies.


Solution

  • After the computer reload and using the Await.result(), everything started to work. Do not know why.