Nest.js依赖更新后Mongoose Schema中model属性编译报错
解决Mongoose Schema中'model'属性与Document内置属性冲突问题
方案一:重命名字段(推荐)
直接修改Schema中的model字段名,避免与Mongoose Document内置的model属性冲突,同时更新代码中所有引用该字段的位置:
// 修改前 const LeasingValueSchema = new Schema({ model: { type: String, required: true } }); // 修改后 const LeasingValueSchema = new Schema({ modelName: { type: String, required: true } });
方案二:使用字段别名(兼容数据库原有字段)
如果无法修改数据库中的字段名,可借助Mongoose的alias选项设置别名,代码中通过别名操作字段,数据库仍保留model字段:
const LeasingValueSchema = new Schema({ model: { type: String, required: true, alias: 'modelAlias' // 定义业务代码中使用的别名 } }); // 示例使用 const leasingValue = new LeasingValue(); leasingValue.modelAlias = 'X1-2024'; console.log(leasingValue.model); // 输出数据库存储的字段值
方案三:自定义Document接口覆盖属性(不推荐)
通过自定义接口强制覆盖Document内置的model属性类型,但此方式可能破坏Mongoose的内置方法,需谨慎使用:
interface LeasingValue extends Document { model: string; // 其他业务属性 } const LeasingValueModel = model<LeasingValue>('LeasingValue', LeasingValueSchema);
内容的提问来源于stack exchange,提问作者Torsten Barthel
相关产品推荐
相关产品推荐

