我正在尝试将 AdminJS 与 Nest.js 集成。
我可以成功登录到 /admin 面板,但是当我尝试访问特定资源时,遇到以下错误:“MongooseError: 操作缓冲在 10000ms 后超时。”
这是我的 package.json 文件的片段,显示了相关依赖项:
"dependencies": {
"@adminjs/express": "^6.0.1",
"@adminjs/mongoose": "^4.0.0",
"@adminjs/nestjs": "^6.0.1",
"@nestjs/common": "^9.0.0",
"@nestjs/core": "^9.0.0",
"@nestjs/mongoose": "^10.0.1",
"@nestjs/platform-express": "^9.0.0",
"@nestjs/swagger": "^7.1.13",
"adminjs": "^7.3.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"express-formidable": "^1.2.0",
"express-session": "^1.17.3",
"mongoose": "^7.6.3",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.2.0"
}
这是我的 app.module.ts 文件的一部分:
(async () => {
const AdminJSMongoose = await import('@adminjs/mongoose');
const AdminJS = (await import('adminjs')).AdminJS;
AdminJS.registerAdapter({
Resource: AdminJSMongoose.Resource,
Database: AdminJSMongoose.Database,
});
})();
const DEFAULT_ADMIN = {
email: '[email protected]',
password: 'password',
};
const authenticate = async (email: string, password: string) => {
if (email === DEFAULT_ADMIN.email && password === DEFAULT_ADMIN.password) {
return Promise.resolve(DEFAULT_ADMIN);
}
return null;
};
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
// Mongoose connection options: https://mongoosejs.com/docs/connections.html
MongooseModule.forRoot(process.env.MONGODB_URL),
// AdminJS version 7 is ESM-only. In order to import it, you have to use dynamic imports.
import('@adminjs/nestjs').then(({ AdminModule }) =>
AdminModule.createAdminAsync({
useFactory: () => ({
adminJsOptions: {
rootPath: '/admin',
resources: [
{
resource: model('Question', QuestionSchema),
options: {
navigation: {
name: 'Sunrise',
},
properties: {
id: { type: 'string' },
text: { type: 'richtext' },
options: { type: 'mixed' },
correctOptionId: { type: 'string' },
image: { type: 'file' },
language: { type: 'string' },
},
},
},
],
},
auth: {
authenticate,
cookieName: 'adminjs',
cookiePassword: 'secret',
},
sessionOptions: {
resave: true,
saveUninitialized: true,
secret: 'secret',
},
}),
}),
),
QuestionsModule,
],
controllers: [AppController],
providers: [
AppService,
{ provide: APP_FILTER, useClass: AllExceptionsFilter },
{ provide: APP_FILTER, useClass: HttpExceptionFilter },
{ provide: APP_FILTER, useClass: ValidationFilter },
],
})
您的数据库未连接...
具体线路:
MongooseModule.forRoot(process.env.MONGODB_URL),
初始化 mongoose 的模块,以通过 MONGODB_URL 的网络连接到 mongodb 实例,该 URL 应指定为环境变量。
你在使用像dotenv这样的东西吗?
如果是这样,您需要在
.env
文件中定义 MONGODB_URL
如果没有,您需要以某种方式为我之前提到的“forRoot”函数提供一个 mongodb url。
如果您还没有本地运行或通过互联网托管的 mongodb 数据库实例,我推荐 MongoDB Atlas。 (我没有以任何方式关联,这只是我使用的,因为他们有强大的免费套餐。)