如何在NestJS的Mongoose Schema函数中注入ConfigService等服务提供者
Mongoose Schema 中使用 Nest 注入服务的解决方案
核心原因
你提供的伪代码无法直接运行,是因为@Prop的配置在类装饰器执行的静态编译阶段就会被解析,此时 Nest 依赖注入容器还未完成初始化,ConfigService 实例不存在,且this的指向也不是 Test 类的实例,根本无法拿到注入的服务。
推荐解决方案:使用异步Schema注册工厂
利用MongooseModule.forFeatureAsync的工厂函数注入依赖,在Schema实例上配置钩子、get/set方法、默认值逻辑即可,示例如下:
1. 调整原Schema定义
去掉@Prop中依赖服务的配置:
// test.schema.ts import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; @Schema() export class Test { @Prop() field: string; } export type TestDocument = Test & Document; export const TestSchema = SchemaFactory.createForClass(Test);
2. 模块中异步注册Schema,注入依赖并配置逻辑
// test.module.ts import { Module } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { Test, TestSchema } from './test.schema'; @Module({ imports: [ MongooseModule.forFeatureAsync([ { name: Test.name, // 导入依赖所在的模块 imports: [ConfigModule], // 声明要注入的服务 inject: [ConfigService], useFactory: (configService: ConfigService) => { const schema = TestSchema; // 1. 实现默认值逻辑:用pre save钩子 schema.pre('save', function(next) { // 注意不要用箭头函数,否则拿不到当前document的this指向 if (!this.field) { this.field = configService.get('defaultField'); } next(); }); // 2. 实现自定义get逻辑 schema.path('field').get(function(value) { return value ? `${value}_${configService.get('FIELD_SUFFIX')}` : value; }); // 3. 实现自定义set逻辑 schema.path('field').set(function(value) { return value ? value.trim() + configService.get('FIELD_PREFIX') : value; }); return schema; } } ]) ] }) export class TestModule {}
注意事项
- 所有依赖注入的服务都需要在
imports中引入对应的模块,才能在inject中声明注入 - 操作document的钩子、get/set方法必须使用普通函数,不能用箭头函数,否则会丢失当前document实例的
this指向
内容的提问来源于stack exchange,提问作者koper89
相关产品推荐
相关产品推荐

