繁体   English   中英

自定义模式的猫鼬typeError

[英]Mongoose typeError with custom Schema

我正在尝试使用discountSchema作为类型。 但我收到此错误:

throw new TypeError('Undefined type at `' + path +
      ^
TypeError: Undefined type at `discount`

但是如果我转换为array类型:

    discount: {
        type: [discountSchema],
        default:{}
    }

有用。

我怎样才能在猫鼬中使用复杂类型呢? 我是否以错误的方式使用此模型? 我如何像这样建模这个对象?

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 设置为猫鼬中的单个属性,它们总是存储在arrays中

与该行为最接近的事情是将您的属性设置为带有refObjectId ,并使用populate方法来获取它。 在这里看看这种方法是如何工作的。


查看嵌入式文档docs

GitHub上有一个公开问题 ,要求您执行所需的行为。

您是否要创建两个模式然后将它们连接起来?

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引用第一个模式
它将获取Discount模型中的属性作为第二个Schema中的Discount属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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