Search code examples
node.jsmongodbmongoosemongoose-schema

How to add different sizes of a product in Mongoose model?


I am using MongoDb and Mongoose to create a model for a practice e-commerce site. Here is what I have so far for my Product model:

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

My question is say I have a shirt which has different size options such as S, M, and L. What is the best way to add this? Also, if I include inventory tracking how would I keep track of all sizes? Thanks in advance and any and all help is appreciated.


Solution

  • There are a lot of different ways to do this, but the easiest is probably via some sub-schema. For example you could create something like:

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

    Then in your product definition:

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

    If you wanted, you could also hook in some logic to ensure that the variant names were unique per product, etc, but this is a basic implementation.