MongoDB Database is not created in Kotlin(Ktor)

1.3k Views Asked by At

please i need help with connecting a mongodb to my ktor application. This is the code i have, as followed from this article: https://himanshoe.com/mongodb-in-ktor

class MongoDataHandler {

val client = KMongo.createClient().coroutine
val database = client.getDatabase("dev")
val userCollection = database.getCollection<User>()

suspend fun adduser(email: String, username: String, password: String): User? {
userCollection.insertOne(User(userId = null, email = email, userName = username, passwordHash = password))
return userCollection.findOne(User::email eq email )
}
suspend fun finduser(id: String): User?{
return userCollection.findOneById(id)
}
}

I installed mongodb as directed from their website. The mongodb is started as a service upon successful install. I run this command "C:\Program Files\MongoDB\Server\5.0\bin\mongo.exe" to use the mongodb. When i check for the available database using "show dbs", i realize that my database(dev) is not listed. This is the dependency am using:

implementation("org.litote.kmongo:kmongo-coroutine:4.2.8")

And this the the error i am getting:

[eventLoopGroupProxy-4-1] INFO  Application - 500 Internal Server Error: 
POST - /user

I guess i am doing something wrong... thanks in advance

2

There are 2 best solutions below

0
On

Try to change your MongoDataHandler to the following, using the MongoClients.create() method, and adding a codecRegistry to your client.

You will not need the connection string settings if you are using the local connection with the default settings:

class MongoDataHandler {
    private val database: MongoDatabase
    private val usersCollection: MongoCollection<User>

    init {
        val pojoCodecRegistry: CodecRegistry = fromProviders(
            PojoCodecProvider.builder()
                .automatic(true)
                .build()
        )

        val codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry)
        val settings: MongoClientSettings = MongoClientSettings.builder()
//            .applyConnectionString("localhost") => add the connection string if not using localhost
            .codecRegistry(codecRegistry)
            .build()

        val mongoClient = MongoClients.create(settings)
        database = mongoClient.getDatabase("dev")
        usersCollection = database.getCollection(User::class.java.name, User::class.java)

    }

Also, if you are not using docker, try to use docker-compose to orchestrate your mongodb container:

version: '3'
services:
  mongo:
    image: mongo:latest
    ports:
      - "27017:27017"

If you want a running example with Ktor/MongoDB take a look in this project

0
On

I assume you are in development mode and trying this in our local machine.

Make sure you have MongoDB installed on the local machine and the local server is running well. Here is a guide for ubuntu.

After successful setup and installation of MongoDB, run this command
mongo --eval 'db.runCommand({ connectionStatus: 1 })'

The output should contain a line as below:
connecting to : mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb

Make sure to add this line while creating client in the ConnectionString like:\

private val client = KMongo.createClient(
    ConnectionString("mongodb://127.0.0.1:27017")
).coroutine

Then try working on your requests/operations with the Ktor, it should work fine.