[英]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'.默认情况下,nest.js 在 class 名称中添加一个“s”,因此集合的名称为“paiss”,但我希望名称为“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() 装饰器
@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?
如果您已经创建了一个集合并想将其从复数名称重命名为一个,您可能想检查这个答案: 如何在 MongoDB 中重命名一个集合? via mongo shell or renaming a collection with mongoDB for Native JS driver.
通过 mongo shell 或使用 mongoDB 为 Native JS 驱动程序重命名集合。
If you want to define your own schema name and avoid this pluralizing
collection form, try to use Mongoose driver.如果您想定义自己的模式名称并避免这种
pluralizing
集合形式,请尝试使用ZCCADCDEDB567ABAE643E15DCF0974E503Z驱动程序。 It allows you to define you own schema / model and name it exactly as you want.它允许您定义自己的架构 / model 并完全按照您的需要命名。 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 .
始终确保您的收藏名称不会破坏任何MongoDB 名称限制。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.