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
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
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.
Related
I am writing an app with a post function.
The post contents will be stored in these paths:
const val PROFILE_PICTURE_PATH = "build/resources/main/static/profile_pictures/"
const val BANNER_IMAGE_PATH = "build/resources/main/static/banner_images/"
const val POST_CONTENT_PATH = "build/resources/main/static/post_contents/"
And Route.kt file with this
static {
resources("static")
}
When I run the server in localhost, I can get the content. However, when I deploy the backend to the server, I can not get images.
i got the same problem every time i try to deploy to heruko
https://prnt.sc/IeH3wooTqqAj
a screenshot from the terminal
1- https://prnt.sc/fqpj3f2lQTz8
2- https://prnt.sc/-710l_bznc2B
this is my application.kt
fun main() {
embeddedServer(Netty, port = 8087, host = "0.0.0.0") {
module {
module()
}
}.start(wait = true)
}
Suppress("unused")
fun Application.module() {
configureKoin()
configureAuth()
configureRouting()
configureSerialization()
configureMonitoring()
configureSession()
}
Prockfile
web: build/install/com.example.googleauth/bin/com.example.googleauth
worker: python scheduler.py
every thing is uptodate and i also add the Config Vars on heroku setting
i also tryed the embedded way and also the engin way same issue
When I click on launcher icon of my android app, its crashes immediately. I check logcat error, its shows Migration is required due to the following errors: - Property 'PrintJobData.jobPageCount' has been removed.I'm using Realm database and language is kotlin. How to overcome this issue.
private val realmConfig: RealmConfiguration = RealmConfiguration.Builder()
.name("database.realm")
// .deleteRealmIfMigrationNeeded()
.schemaVersion(1)
.build()
private var realm: Realm = Realm.getInstance(realmConfig)
you can delete your realm if a migration is needed:
.deleteRealmIfMigrationNeeded()
or you can write a custom migration for your realm and each change you make to your database MUST be handled in migration.
NOTE: remember after your changes to your database you have to update schemaVersion and also add your custom migration to RealmConfiguration.Builder() like bellow:
val config = RealmConfiguration.Builder()
.name("yourRealmName.realm")
.schemaVersion(2)
.migration(CustomMigration())
.build()
you can learn how to write migration from this and the original document
I'm using ktor 0.9.5. I'm trying a simple example. But when a try to connect to the server i get ERR_EMPTY_RESPONSE. This is my code.
fun main(args: Array<String>) {
embeddedServer(Netty, port = 8080, host = "localhost") {
install(DefaultHeaders)
install(CallLogging)
routing {
get(path = "/") {
call.respondText("Hello World!!")
}
}
}.start()
}
Doing some research I found that changing the project to Maven fix the problem, but because of rules of my organization I can't do it. Any other solution... Thanks before hand.
I have added a println("sometext") before call.respondText("Hello World!!") and it's never executed.
With ERR_EMPTY_RESPONSE error, I guess you are requesting the server from a Google Chrome browser. Right ?
Are you trying to connect to the server from another computer? If so it won't work because you have set the server to only respond for requests coming from localhost.
embeddedServer(Netty, port = 8080, host = "localhost")
Even if you add a println() it won't execute.
Try to remove host = "localhost" from embeddedServer() parameters an re-test.
Here's the code I'm using to fetch:
public static void GitFetch()
{
var creds = new UsernamePasswordCredentials()
{Username = "user",
Password = "pass"};
var fetchOpts = new FetchOptions {Credentials = creds};
using (repo = new Repository(#"C:\project");)
{
repo.Network.Fetch(repo.Network.Remotes["origin"], fetchOpts);
}
}
but it fails during fetch with the following exception:
LibGit2Sharp.LibGit2SharpException: Too many redirects or authentication replays
Result StackTrace:
at LibGit2Sharp.Core.Ensure.HandleError(Int32 result)
at LibGit2Sharp.Core.Proxy.git_remote_fetch(RemoteSafeHandle remote, Signature signature, String logMessage)
at LibGit2Sharp.Network.DoFetch(RemoteSafeHandle remoteHandle, FetchOptions options, Signature signature, String logMessage)
at LibGit2Sharp.Network.Fetch(Remote remote, FetchOptions options, Signature signature, String logMessage)
I have verified that the config file has the required remote name and that git fetch works from the command line. I found that the exception originates from libgit2\src\transport\winhttp.c but I couldn't come up with a workaround/solution.
I tried #Carlos' suggestion in the following way:
public static void GitFetch()
{
var creds = new UsernamePasswordCredentials()
{Username = "user",
Password = "pass"};
CredentialsHandler credHandler = (_url, _user, _cred) => creds;
var fetchOpts = new FetchOptions { CredentialsProvider = credHandler };
using (repo = new Repository(#"C:\project");)
{
repo.Network.Fetch(repo.Network.Remotes["origin"], fetchOpts);
}
}
I could fetch from public repos on github as well as from password protected private repos on bitbucket; however, I couldn't do the same for the repositories hosted over LAN at work. Turns out they were configured in a way which does not accept UsernamePasswordCredentials provided by libgit2sharp. The following modification allowed me to fetch from repositories over LAN:
CredentialsHandler credHandler = (_url, _user, _cred) => new DefaultCredentials();
(I'm trying to find out what is the exact difference between the two; if I get further insight into it, I'll update the answer.)
The shim that should make the Credentials option work is currently buggy (and is deprecated anyway), pass a CredentialsProvider instead as a callback.
This seems to be a very common error message.
We were getting it on pushes to GitHub, because credentials were disabled for security:
https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/
We've solved it by enabling SAML SSO and doing the push outside the C# code, but perhaps using SSH keys somehow with the library or personal access tokens fixes the problem too.