NestJs/Mongoose同一模型多Schema实现方案咨询
解决NestJS中Mongoose同一集合使用多个Schema的问题
你遇到的Cannot overwrite 'foo' model once compiled错误,本质原因是Mongoose中同一个模型名称只能对应一个编译后的Schema——当你重复注册同名模型(这里都是'foo')时,Mongoose会尝试覆盖已编译的模型,这是不允许的。
不过要实现“同一个集合对应不同Schema”的需求是完全可行的,核心思路是给每个Schema注册不同的模型名称,同时指定它们指向同一个MongoDB集合。
步骤1:调整模型注册代码
修改MongooseModule.forFeature的配置,给两个Schema分别起不同的模型名(比如'Foo1'和'Foo2'),并通过collection参数指定它们共用同一个集合'foo':
import { Module } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; import { Schema1, Schema2 } from './your-schemas-file'; @Module({ imports: [ MongooseModule.forFeature([ { name: 'Foo1', schema: Schema1, collection: 'foo' }, { name: 'Foo2', schema: Schema2, collection: 'foo' }, ]), // 其他模块导入... ], }) export class YourModule {}
步骤2:在服务中注入两个模型
在你的服务类里,通过不同的模型名称注入对应的实例:
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { Schema1, Schema2 } from './your-schemas-file'; @Injectable() export class YourService { constructor( @InjectModel('Foo1') private readonly foo1Model: Model<Schema1>, @InjectModel('Foo2') private readonly foo2Model: Model<Schema2>, ) {} // 示例:用Schema1查询数据 async findWithSchema1() { return this.foo1Model.find({ type: 'someValue' }).exec(); } // 示例:用Schema2插入数据 async createWithSchema2(data: any) { const doc = new this.foo2Model(data); return doc.save(); } }
额外说明:正确定义Mongoose Schema
注意你的示例中Schema的写法不太规范,实际需要用Mongoose的Schema构造函数来创建:
import { Schema } from 'mongoose'; export const Schema1 = new Schema({ type: { type: String, index: true, default: 'someValue' }, data: { mapname: String } }); export const Schema2 = new Schema({ type: { type: String, index: true, default: 'anotherValue' }, data: { showStats: Boolean, email: String } });
这样配置后,两个模型会操作同一个foo集合,但各自使用不同的Schema来校验、处理数据,完美解决你的需求。
内容的提问来源于stack exchange,提问作者Alexandre Fradette
相关产品推荐
相关产品推荐

