I have a dockerized database :
mongodb:
image: mongo:latest
container_name: mongoose-db
ports:
- "27017:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: 1234
volumes:
- mongodb_data:/data/db
I have a Nest.JS project running on http://localhost:3000/ and not inside a dockerized stack.
I want to correctly connect my Nest.JS project to the database :
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
MongooseModule.forRoot('mongodb://root:1234@localhost:27017', {
dbName: 'myappdb',
auth: {
username: 'root',
password: '1234',
},
}),
UsersModule,
AuthModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {
}
I tried this confi :
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
MongooseModule.forRoot('mongodb://root:[email protected]:27017/myappdb'),
UsersModule,
AuthModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
I’m getting this error :
[Nest] 16036 – 20/08/2023 14:40:34 ERROR [ExceptionHandler] Authentication failed. MongoServerError: Authentication failed.
at Connection.onMessage (D:Mes_POCStoken-auth-appnode_modulesmongodbsrccmapconnection.ts:450:20)
at MessageStream. (D:Mes_POCStoken-auth-appnode_modulesmongodbsrccmapconnection.ts:268:56)
at MessageStream.emit (node:events:514:28)
at processIncomingData (D:Mes_POCStoken-auth-appnode_modulesmongodbsrccmapmessage_stream.ts:194:14)
at MessageStream._write (D:Mes_POCStoken-auth-appnode_modulesmongodbsrccmapmessage_stream.ts:71:5)
at writeOrBuffer (node:internal/streams/writable:392:12)
at _write (node:internal/streams/writable:333:10)
at MessageStream.Writable.write (node:internal/streams/writable:337:10)
at Socket.ondata (node:internal/streams/readable:766:22)
at Socket.emit (node:events:514:28)
What is the correct database url ?
3
Answers
It was an problem in docker compose conf file :
And the good root is :
You need to use
127.0.0.1
instead oflocalhost
in your mongoose connection.That means, you need to use:
According to the error that has been displayed the Credentials for mongo dB aren’t corrects do double check please.