I install the mongodb software on my own Ubuntu server and I get the mongo string just like this mongodb://xxx:[email protected]:27017
,when I type this string in my local terminal and use mongosh mongodb://xxx:[email protected]:27017
, it works fine and the connection is success. But when I use this mongodb string in my nestjs project, when I run npm run start
, the terminal output MongoServerError: Authentication failed.
app.module.ts
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => {
const username = configService.get('MONGO_USER');
const password = configService.get('MONGO_PASS');
const database = configService.get('MONGO_DATABASE');
const host = configService.get('MONGO_HOST');
const port = configService.get('MONGO_PORT');
return {
type: 'mongodb',
host,
port,
username,
password,
database,
entities: [__dirname '/**/*.entity{.ts,.js}'],
synchronize: true,
};
},
The mongodb version is 4.1.3, TypeOrm version is 0.2.38. Does anyone know what is the problem and how to solve it? Thank u.
CodePudding user response:
Maybe you should try to use the Database URL connection string instead of host, port, username, password, ...
So instead of using this
return {
type: 'mongodb',
host,
port,
username,
password,
database,
entities: ...
...
}
you should use this
return {
type: "mongodb",
url: configService.get("DATABASE_URL"),
entities: ...
...
}
CodePudding user response:
I have figure out what the problem is, as the authSource of my mongodb is not the same one with the database to save data. So I should set the authSource option to admin, then it works.
return {
type: 'mongodb',
host,
port,
username,
password,
database,
authSource: 'admin',
entities: [__dirname '/**/*.entity{.ts,.js}'],
synchronize: true,
};