I am trying to build my listings model in a way where it restricts users to only select a subcategory if it exists in the parent array list. I can do this when I am building the API end point fine but I wanted to see if its possible to do this within the Model itself.
here is an example:
If(a user selects parent category household from the parent enum category array) .then(set ENUM array based of the parent category)
Code Reference:
Model:
var categories = require(settings.PROJECT_DIR + 'controllers/data/categories');
var ListingSchema = mongoose.Schema({
data: {
category: {
parent: {
type: String,
enum: categories.parent(),
required: true
},
sub: {
type: String,
enum: categories.sub("household"), // should be this.data.category.parent instead of hard coded value
required: true
}
},
}
}
The Categories Array:
module.exports.categories = [
{ "household" : ["repair", "carpentry", "housecleaning", "electrical", "handymen", "movers", "plumbing", "gardening/pool"] },
{ "automotive" : ["autobody", "mechanics", "towing"] },
{ "creative" : ["art", "cooking", "film", "graphic_design", "marketing", "music", "writing"] },
{ "tech" : ["tech", "repair", "web_design", "web_development"] },
{ "events" : ["artist", "florist", "musician", "photography", "planning", "venue"] },
{ "legal" : ["accounting", "advising", "investments", "consulting", "real_estate"] },
{ "health" : ["beauty", "fitness", "nutrition", "therapeutic"] },
{ "pets" : ["grooming", "sitter", "trainer", "walker"] }
];
// @returns parent categories
module.exports.parent = function() {
var self = this;
var parentCategories = [];
for(var i in self.categories) {
parentCategories.push( Object.keys(self.categories[i])[0] );
}
return parentCategories;
}
// @returns sub categories based of parent input
module.exports.sub = function(parent) {
var self = this;
var subCategories = [];
for(var i in self.categories) {
if(self.categories[i][parent]) {
return self.categories[i][parent];
}
}
}