[英]MongoDB and Nest.js: Define a custom name for a collection
我有这样的架构:
@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 在 class 名称中添加一个“s”,因此集合的名称为“paiss”,但我希望名称为“paises”。
在模块上我试过这个:
@Module({
imports: [
MongooseModule.forFeature([{ name: 'paises', schema: PaisSchema }]),
],
但它没有用。 我怎么解决这个问题?
我找到了一个解决方案,只需像这样设置 @Schema() 装饰器
@Schema({ collection: 'paises' })
首先。 如果您已经创建了一个集合并想将其从复数名称重命名为一个,您可能想检查这个答案: 如何在 MongoDB 中重命名一个集合? 通过 mongo shell 或使用 mongoDB 为 Native JS 驱动程序重命名集合。
如果您想定义自己的模式名称并避免这种pluralizing
集合形式,请尝试使用ZCCADCDEDB567ABAE643E15DCF0974E503Z驱动程序。 它允许您定义自己的架构 / model 并完全按照您的需要命名。 为此,请使用以下代码段:
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 名称限制。
这不是真的
@Schema({ collection: 'paises' })
您可以在模块文件中收集名称
MongooseModule.forFeature([{name : 'paises' , schema : PaisSchema }])
并在服务文件中:
@InjectModel('paises') public model: paisesModel<paisesDocument>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.