2017-10-22 71 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] 
}); 

如果你願意,你也可以勾在一些邏輯,以確保不同名稱爲每個產品的獨特,等等,但這是一個基本的實現。

相關問題