【问题标题】:NestJs/Mongoose Multiple schemas for same modelNestJs/Mongoose 同一模型的多个模式
【发布时间】:2018-10-22 01:45:48
【问题描述】:

如果有一种方法可以为同一模型提供多个模式,我正在徘徊。在我的一个模块中,我有两个不同的模式试图访问同一个模型。但是当我这样做时:

@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') 引用,这将是模棱两可的。你想如何决定应该使用哪个模式?你想达到什么目标?
  • 我终于意识到,命名只是用来在服务内部的MongooseModuleInjectModel 之间创建一个“链接”。我认为它必须与集合的名称相同。
  • 也许将此添加为答案并接受它。人们花时间在一个没有答案的问题上,然后发现它已经解决了,这是令人沮丧的。

标签: javascript node.js mongoose mongoose-schema nestjs


【解决方案1】:

例如在服务中使用模型时,它仅由名称 @InjectModel('foo') 引用,因此必须是明确的。您不能定义两个具有相同名称的模型。

正如你所说,但是有可能有两个模型指向同一个集合,因为集合名称是一个可选参数,请参阅source code

static forFeature(
  models: { name: string; schema: any; collection?: string }[] = [],
  connectionName: string = DefaultDbConnectionToken,
)

【讨论】:

    猜你喜欢
    • 2021-11-15
    • 1970-01-01
    • 2020-02-26
    • 2020-10-02
    • 2020-06-16
    • 2021-06-21
    • 2022-07-11
    • 1970-01-01
    • 2015-04-30
    相关资源
    最近更新 更多