2017-10-22 128 views
0

我正在使用MongoDb和Mongoose为实践电子商务网站创建模型。以下是我迄今为止对我的产品型号:如何在Mongoose模型中添加不同尺寸的产品?

var mongoose = require('mongoose'); 

module.exports = mongoose.model('Product',{ 
    imagePath: {type: String, required: true}, 
    title: {type: String, required: true}, 
    description: {type: String, required: true}, 
    price: {type: Number, required: true} 
}); 

我的问题是说我有有不同的大小的选项,如S,M衬衫,和L.什么是添加这个最好的方法是什么?另外,如果我包含库存跟踪,我将如何跟踪所有尺寸?在此先感谢和任何和所有帮助表示赞赏。

回答

0

有很多不同的方式来做到这一点,但最简单的可能是通过一些子模式。例如,你可以创建类似:

const ProductVariant = new mongoose.Schema({ 
    name: String, // If you're certain this will only ever be sizes, you could make it an enum 
    inventory: Number 
}); 

然后在您的产品定义:

module.exports = mongoose.model('Product',{ 
    imagePath: {type: String, required: true}, 
    title: {type: String, required: true}, 
    description: {type: String, required: true}, 
    price: {type: Number, required: true}, 
    variants: [ProductVariant] 
}); 

如果你愿意,你也可以勾在一些逻辑,以确保不同名称为每个产品的独特,等等,但这是一个基本的实现。

相关问题