Skip to content

Instantly share code, notes, and snippets.

@bnielsen1965
Created April 27, 2019 03:22
Show Gist options
  • Save bnielsen1965/7975390e2731e3fb14028dc431bdf006 to your computer and use it in GitHub Desktop.
Save bnielsen1965/7975390e2731e3fb14028dc431bdf006 to your computer and use it in GitHub Desktop.
Adding a sub-schema to use in place of a Mixed type...
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const schemaOptions = {
timestamps: true
};
// this defines a sub-schema that will be used inside the Product schema...
const variantSchema = new Schema({
qty: { type: Number, required: true },
price: {
type: Number,
required: true
},
originalPrice: {
required: false,
type: Number
},
size: { type: String }
});
const productSchema = new Schema({
productTitle: {
type: String,
required: true,
index: true
},
slug: {
type: String
},
qty: { type: Number, required: true },
desc: {
type: String,
required: true,
index: true
},
category: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
originalPrice: {
required: false,
type: Number
},
// using the variantSchema to define an array of variants
variants: [{ type: variantSchema, excludeIndexes: true }],
// productOptions: {
// type: Schema.Types.Mixed
// },
defaultImg: {
type: String,
default: ''
},
publish: String,
freeShipping: String,
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
listingType: {type: String, default: 'product'}
}, schemaOptions);
productSchema.index({productTitle: 'text', desc: 'text'});
module.exports = mongoose.model('Product', productSchema);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment