简体   繁体   English

自定义模式的猫鼬typeError

[英]Mongoose typeError with custom Schema

I'm trying to use discountSchema as a type. 我正在尝试使用discountSchema作为类型。 But I'm getting this error: 但我收到此错误:

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

but if I transform to type array : 但是如果我转换为array类型:

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

it works. 有用。

How can I use complex type in mongoose as this? 我怎样才能在猫鼬中使用复杂类型呢? Am I using this model in a wrong way? 我是否以错误的方式使用此模型? How can I model this object like this? 我如何像这样建模这个对象?

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:{}
    }
};

You cant't set embedded documents stored as single property in mongoose, they are always stored in arrays . 您不能存储的embedded documents 设置为猫鼬中的单个属性,它们总是存储在arrays中

The closest thing to this behaviour is setting your property to an ObjectId with a ref and using the populate method to fetch it. 与该行为最接近的事情是将您的属性设置为带有refObjectId ,并使用populate方法来获取它。 Take a look here to see how this approach works. 在这里看看这种方法是如何工作的。


Check out embedded documents docs . 查看嵌入式文档docs

There is an open issue on GitHub requesting the behaviour you want. GitHub上有一个公开问题 ,要求您执行所需的行为。

are you trying to create two Schemas then wire them up? 您是否要创建两个模式然后将它们连接起来?

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); 

I reference the discount in the second schema to reference to the first schema by the ObjectId 我引用第二个模式中的折扣以通过ObjectId引用第一个模式
It will fetch the properties in the Discount model as a discount property in the second Schema. 它将获取Discount模型中的属性作为第二个Schema中的Discount属性。

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

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