【问题标题】:MongoDB and Nest.js: Define a custom name for a collectionMongoDB 和 Nest.js:为集合定义自定义名称
【发布时间】:2020-11-23 20:06:04
【问题描述】:

我有这样的架构:

    @Schema()
    export class Pais extends Document {
      @Prop(
        raw({
          codigo: { type: String, index: true, unique: true },
        }),
      )
      @Prop()
      descripcion: string;
    }
    
    export const PaisSchema = SchemaFactory.createForClass(Pais);
    
    PaisSchema.plugin(uniqueValidator, { message: `{PATH} debe ser único` });

默认情况下,nest.js 会在类名中添加一个 's',因此集合的名称将是 'paiss',但我希望名称是 'paises'。

在我尝试过的模块上:

    @Module({
      imports: [
        MongooseModule.forFeature([{ name: 'paises', schema: PaisSchema }]),
      ],

但它没有用。我该如何解决这个问题?

【问题讨论】:

标签: javascript mongodb collections nestjs


【解决方案1】:

我找到了解决方案,只需要像这样设置 @Schema() 装饰器

@Schema({ collection: 'paises' })

【讨论】:

    【解决方案2】:

    首先。如果您已经创建了一个集合并想将其从复数名称重命名为一个,您可能需要检查以下答案:How can I rename a collection in MongoDB? via mongo shell 或 renaming a collection with mongoDB for Native JS driver。

    如果您想定义自己的模式名称并避免使用这种pluralizing 集合形式,请尝试使用Mongoose 驱动程序。它允许您定义自己的模式/模型并完全按照您的需要命名。为此,请使用下面的 sn-p:

    let schema = new mongoose.Schema({
        _id: {
            type: String,
        },
        other_field: String
    },{
        /** Schema options*/
        timestamps: true
    });
    
    let model_db = mongoose.model('collection_name', schema, 'collection');
    

    但是!始终确保您的集合名称不会破坏任何 MongoDB name restictions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-18
      • 1970-01-01
      • 2015-08-21
      • 2015-08-05
      • 2021-07-10
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      相关资源
      最近更新 更多