1

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

  • Are you able to connect to a MongoDB database without the Ktor? If so, please share a code for a complete project. – Aleksei Tirman Jul 26 '21 at 11:29
  • Yes, i am able to connect to mongodb without Ktor. Here is a link to the project.. https://github.com/Toluxpersia/Link.. Thnks – Solomon Tolu Samuel Jul 28 '21 at 18:35
  • If I pass environment variables `JWT_SECRET` and `SECRET_KEY` while running your application with valid values, then `java.lang.IllegalStateException: generation for id property type not supported : class kotlin.Int` is thrown in the `adduser` method. – Aleksei Tirman Jul 29 '21 at 09:26
  • Also, please make sure you send a request with `Content-type: application/x-www-form-urlencoded`. – Aleksei Tirman Jul 29 '21 at 09:59
  • Can you try using a String variable for the JWT_SCRETE and SECRET_KEY constants? and i use Postman to make requests appropriately. But ultimately, am i creating and initializing the database correctly? – Solomon Tolu Samuel Jul 30 '21 at 14:37
  • I use random strings for those environment variables. I believe you do it correctly. – Aleksei Tirman Jul 30 '21 at 16:14
  • I found another solution using docker compose...thanks alot for your help – Solomon Tolu Samuel Jul 31 '21 at 14:09

2 Answers2

0

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

valdeci
  • 13,962
  • 6
  • 55
  • 80
0

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.

4shutosh
  • 46
  • 3