带有自定义模式的Mongoosetypes错误
我正在尝试使用discountSchema
作为types。 但是我得到这个错误:
throw new TypeError('Undefined type at `' + path + ^ TypeError: Undefined type at `discount`
但如果我转换为array
types:
discount: { type: [discountSchema], default:{} }
有用。
如何在mongoose中使用复杂types? 我是否以错误的方式使用这个模型? 我该如何模拟这个对象?
var discountSchema = new Schema({ type: {type: String,default:'' }, quantity: {type: Number,default:0 }, value: {type: Number,default:0 } }); var objectEncomendaPropertiesSchema = { recheios:{ type:[String], default: [], select: true }, availableEncomenda: { type: Boolean, default:false }, discount: { type: discountSchema, default:{} } };
您不能将 embedded documents
作为单个属性存储在mongoose中,它们始终存储在数组中 。
最接近这种行为的是使用ref
将你的属性设置为ObjectId
,并使用populate
方法来获取它。 看看这里看看这种方法是如何工作的。
查看embedded式文档文档 。
在GitHub上有一个开放的问题 ,要求你想要的行为。
你想创build两个模式,然后把它们连接起来吗?
var discountSchema = new Schema({ type: {type: String,default:'' }, quantity: {type: Number,default:0 }, value: {type: Number,default:0 } }); mongoose.model('Discount', discountSchema); var objectEncomendaPropertiesSchema = new Schema({ recheios:{ type: String, default: '', select: true }, availableEncomenda: { type: Boolean, default:false }, discount: { type: Schema.Types.ObjectId, ref: 'Discount' } }) mongoose.model('objectEncomendaProperties', objectEncomendaPropertiesSchema);
我引用第二个模式中的折扣来引用ObjectId的第一个模式
它将获取折扣模型中的属性作为第二个模式中的折扣属性。