NestJs/Mongoose 同一模型的多个模式
NestJs/Mongoose Multiple schemas for same model
我在想是否有办法为同一模型设置多个模式。在我的一个模块中,我有两个不同的模式试图访问同一个模型。但是当我这样做时:
@Module({
imports: [
MongooseModule.forFeature([
{name: 'foo', schema: Schema1},
{name: 'foo', schema: Schema2},
]), ......
我收到错误 Cannot overwrite 'foo' model once compiled
这是我的模式示例:
export class Schema1{
type: { type: string, index: true, default: 'someValue'},
data: {mapname: string}
}
export class Schema2{
type: {type: string, index: true, default: 'anotherValue'}.
data: {showStats: boolean, email: string}
}
例如在服务中使用模型时,它仅通过名称 @InjectModel('foo')
引用,因此必须明确。您不能定义两个具有相同名称的模型。
正如您所说,但是可以让两个模型指向同一个集合,因为集合名称是一个可选参数,请参阅 source code:
static forFeature(
models: { name: string; schema: any; collection?: string }[] = [],
connectionName: string = DefaultDbConnectionToken,
)
我在想是否有办法为同一模型设置多个模式。在我的一个模块中,我有两个不同的模式试图访问同一个模型。但是当我这样做时:
@Module({
imports: [
MongooseModule.forFeature([
{name: 'foo', schema: Schema1},
{name: 'foo', schema: Schema2},
]), ......
我收到错误 Cannot overwrite 'foo' model once compiled
这是我的模式示例:
export class Schema1{
type: { type: string, index: true, default: 'someValue'},
data: {mapname: string}
}
export class Schema2{
type: {type: string, index: true, default: 'anotherValue'}.
data: {showStats: boolean, email: string}
}
例如在服务中使用模型时,它仅通过名称 @InjectModel('foo')
引用,因此必须明确。您不能定义两个具有相同名称的模型。
正如您所说,但是可以让两个模型指向同一个集合,因为集合名称是一个可选参数,请参阅 source code:
static forFeature(
models: { name: string; schema: any; collection?: string }[] = [],
connectionName: string = DefaultDbConnectionToken,
)