NestJS中AdminJS无法从MongoDB获取数据的问题求助
解决NestJS中AdminJS搭配Mongoose的
products.find()超时问题 问题场景
在NestJS项目中使用AdminJS与Mongoose,相关配置如下:
产品模型代码:
const ProductModel = model<IProduct>('product', ProductSchema);
AdminJS资源配置:
resources: [ { resource: ProductModel, options: { navigation: { name: null }, show: { before: async (request, response, context) => { throw new Error( 'Data fetching has been disabled for this resource', ); }, handler: async (request, response, context) => { return { records: [], }; }, }, list: { before: async (request, response, context) => { throw new Error( 'Data fetching has been disabled for this resource', ); }, handler: async (request, response, context) => { return { records: [], }; }, }, }, ]
出现错误日志:
[Nest] 23592 - 04/12/2023, 11:16:57 AM ERROR [ExceptionsHandler] Operation `products.find()` buffering timed out after 10000ms MongooseError: Operation `products.find()` buffering timed out after 10000ms at Timeout. (C:\Users\user\Documents\backend\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:185:23) at listOnTimeout (node:internal/timers:559:17) at processTimers (node:internal/timers:502:7)
解决方案
1. 确保Mongoose数据库连接优先完成
NestJS中需保证MongooseModule.forRoot()在AdminJS相关模块之前初始化,避免模型在数据库未连接时执行查询。检查模块导入顺序,将Mongoose连接模块放在AdminJS模块的前面。
2. 修改AdminJS配置,正确禁用数据查询操作
原配置通过before钩子抛错的方式无法完全阻止AdminJS触发底层Mongoose查询,改为直接禁用对应操作或自定义无查询的处理逻辑:
resources: [ { resource: ProductModel, options: { navigation: { name: null }, actions: { // 禁用列表操作并返回空结果 list: { isAccessible: () => false, handler: async () => ({ records: [], total: 0 }) }, // 禁用详情操作并返回空记录 show: { isAccessible: () => false, handler: async () => ({ record: null }) } } } } ]
3. 验证数据库连接有效性
检查MongoDB连接字符串是否正确,确认数据库服务正常运行。可在NestJS启动时添加连接状态日志,确保Mongoose已成功建立连接:
import { Connection, InjectConnection } from 'mongoose'; import { Module, OnModuleInit } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; @Module({ imports: [MongooseModule.forRoot('mongodb://localhost:27017/your-db-name')], }) export class DatabaseModule implements OnModuleInit { constructor(@InjectConnection() private readonly connection: Connection) {} async onModuleInit() { if (this.connection.readyState === 1) { console.log('MongoDB连接成功'); } else { console.error('MongoDB连接失败'); } } }
内容的提问来源于stack exchange,提问作者guseinxo
相关产品推荐
相关产品推荐

