NestJS + Mongoose执行查询时无响应挂起问题求助
问题描述
运行基于Node 16.17.0、MongoDB 6.0.1的NestJS应用,MongoDB以Docker容器部署在Windows的WSL2(Ubuntu 20.04 LTS)环境,Node通过NVM安装在Ubuntu系统内。
NestJS应用能正常启动加载模块,但执行查询时无响应挂起,无错误信息,try/catch无法捕获异常,也无超时提示;将Node应用打包为Docker容器运行时问题依旧。
相关配置信息:
NestJS启动日志
[Nest] 11168 - 09/24/2022, 4:50:57 PM LOG [NestFactory] Starting Nest application... [Nest] 11168 - 09/24/2022, 4:50:57 PM LOG [InstanceLoader] AppModule dependencies initialized +36ms [Nest] 11168 - 09/24/2022, 4:50:57 PM LOG [InstanceLoader] MongooseModule dependencies initialized +1ms [Nest] 11168 - 09/24/2022, 4:50:57 PM LOG [InstanceLoader] PosterrModule dependencies initialized +0ms [Nest] 11168 - 09/24/2022, 4:50:57 PM LOG [InstanceLoader] MongooseCoreModule dependencies initialized +11ms [Nest] 11168 - 09/24/2022, 4:50:57 PM LOG [InstanceLoader] MongooseModule dependencies initialized +1ms [Nest] 11168 - 09/24/2022, 4:50:57 PM LOG [RoutesResolver] PostController {/test}: +2ms [Nest] 11168 - 09/24/2022, 4:50:57 PM LOG [RouterExplorer] Mapped {/test, GET} route +2ms [Nest] 11168 - 09/24/2022, 4:50:57 PM LOG [RouterExplorer] Mapped {/test/:id, GET} route +1ms [Nest] 11168 - 09/24/2022, 4:50:57 PM LOG [RouterExplorer] Mapped {/test, POST} route +1ms [Nest] 11168 - 09/24/2022, 4:50:57 PM LOG [RouterExplorer] Mapped {/test/:id, PUT} route +1ms [Nest] 11168 - 09/24/2022, 4:50:57 PM LOG [RouterExplorer] Mapped {/test/:id, DELETE} route +0ms [Nest] 11168 - 09/24/2022, 4:50:57 PM LOG [NestApplication] Nest application successfully started +2ms
docker-compose.json
version: '3.3' services: MongoDB: image: 'mongo:latest' restart: 'unless-stopped' env_file: './.env' environment: - MONGO_DATABASE=test ports: - 27017:27017 volumes: - mongodata:/data/db volumes: mongodata: {}
app.module.ts 连接配置
@Module({ imports: [ MongooseModule.forRoot('mongodb://localhost:27017/test'), TeestModule, ], })
TestModule 模型配置
@Module({ imports: [ MongooseModule.forFeature([ { name: 'Test', schema: testSchema}, ]), ], controllers: [TestController] })
Schema 定义
export const testSchema: Schema = new Schema( { id: { type: Types.ObjectId, required: false }, text: string }, { timestamps: true }, ); export interface TextDocumentInterface extends Document { id?: Types.ObjectId; text: string; createdAt: Date; updateddAt?: Date; deletedAt?: Date; } export default model<TextDocumentInterface >('Test', testSchema);
仓库类模型注入
@Injectable(); export default class TestRepository { constructor( @InjectModel('Test') readonly model: Model<TextDocumentInterface>, ) { } }
执行以下查询时应用完全挂起:
await this.model.find({}).limit(10);
解决思路
- 修正MongoDB连接地址
- 若NestJS在WSL2内运行,
localhost指向WSL2内部,需通过docker inspect <mongo容器ID>获取容器IP,将连接地址替换为mongodb://<容器IP>:27017/test;若应用也打包成Docker容器,在同一docker-compose网络下,直接用服务名MongoDB作为主机名,即mongodb://MongoDB:27017/test。
- 若NestJS在WSL2内运行,
- 匹配Mongoose与MongoDB版本兼容性
- MongoDB 6.0.x需搭配Mongoose 6.x或7.x版本(Mongoose 7.x最低支持Node 14.17)。检查项目Mongoose版本,若过低,执行
npm install mongoose@^6.8.0升级到兼容版本。
- MongoDB 6.0.x需搭配Mongoose 6.x或7.x版本(Mongoose 7.x最低支持Node 14.17)。检查项目Mongoose版本,若过低,执行
- 修复Schema和模型定义错误
- Schema中
text字段缺少类型声明,改为text: { type: String }; - 接口
TextDocumentInterface中updateddAt拼写错误,修正为updatedAt; - 删除Schema文件中的
export default model<TextDocumentInterface>('Test', testSchema);,避免与MongooseModule.forFeature()的模型注册冲突。
- Schema中
- 添加连接超时与日志配置
- 在
MongooseModule.forRoot()中加入超时和日志参数,便于排查连接问题:MongooseModule.forRoot('mongodb://.../test', { connectTimeoutMS: 5000, socketTimeoutMS: 5000, loggerLevel: 'debug' })
- 在
- 检查WSL2网络连通性
- 在WSL2终端执行
mongosh mongodb://localhost:27017/test,验证是否能正常连接并执行查询。若失败,重启WSL2和Docker服务,检查端口转发是否正常。
- 在WSL2终端执行
- 修正仓库类装饰器
- 仓库类的
@Injectable();缺少括号,改为@Injectable(),确保Nest能正确识别并注入依赖。
- 仓库类的
内容的提问来源于stack exchange,提问作者Maximiliano Nunes Catarino
相关产品推荐
相关产品推荐

