简体   繁体   中英

MongoDB and Nest.js: Define a custom name for a collection

I have a schema like this:

    @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` });

By default nest.js add an 's' to the class name, so it would be 'paiss' for the collection, but I want the name to be 'paises'.

On the module I tried this:

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

but it didn't work. How can I solve this problem?

i found a solution, just had to set the @Schema() decorator like this

@Schema({ collection: 'paises' })

First of all. If you have already create a collection and want to rename it from plural name for to a single one, you might wanna check this answer: How can I rename a collection in MongoDB? via mongo shell or renaming a collection with mongoDB for Native JS driver.

If you want to define your own schema name and avoid this pluralizing collection form, try to use Mongoose driver. It allows you to define you own schema / model and name it exactly as you want. To achieve this, use snippet below:

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

let model_db = mongoose.model('collection_name', schema, 'collection');

But! Always make sure that your collection name doesn't break any MongoDB name restictions .

this is Not true

@Schema({ collection: 'paises' })

You can collection name in module file

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

and in service File:

@InjectModel('paises') public model: paisesModel<paisesDocument>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM