我在我自己的 Ubuntu 服務器上安裝了 mongodb 軟體,我得到了這樣的 mongo 字串mongodb://xxx:[email protected]:27017,當我在本地終端中輸入這個字串并使用時mongosh mongodb://xxx:[email protected]:27017,它作業正常并且連接成功。但是當我在我的 nestjs 專案中使用這個 mongodb 字串時,當我運行時npm run start,終端輸出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,
};
},
mongodb 版本為 4.1.3,TypeOrm 版本為 0.2.38。有誰知道是什么問題以及如何解決它?感謝你。
uj5u.com熱心網友回復:
也許您應該嘗試使用資料庫 URL 連接字串而不是主機、埠、用戶名、密碼……
所以不要使用這個
return {
type: 'mongodb',
host,
port,
username,
password,
database,
entities: ...
...
}
你應該用這個
return {
type: "mongodb",
url: configService.get("DATABASE_URL"),
entities: ...
...
}
uj5u.com熱心網友回復:
我已經弄清楚問題是什么,因為我的 mongodb 的 authSource 與用于保存資料的資料庫不同。所以我應該將 authSource 選項設定為 admin,然后它就可以作業了。
return {
type: 'mongodb',
host,
port,
username,
password,
database,
authSource: 'admin',
entities: [__dirname '/**/*.entity{.ts,.js}'],
synchronize: true,
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/322891.html
