在同一模型中设置基于另一个Enum数组的枚举数组 - Mongoose

时间:2017-06-10 23:57:29

标签: javascript mongoose mongoose-schema

我正在尝试构建我的列表模型,它限制用户只选择父类数组列表中存在的子类别。我可以在构建API端点时做到这一点,但我想看看它是否可以在模型本身内完成。

这是一个例子:

如果(用户从父枚举类别数组中选择父类别家庭) .then(根据父类别设置ENUM数组)

代码参考:

型号:

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
            }
        },
    }
}

分类数组:

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

1 个答案:

答案 0 :(得分:1)

模型中无法实现。

mongoose.Schema()方法根据提供给它的参数创建一个Schema对象。并且创建的对象存储在ListingSchema中。由于在第一次执行mongoose.Schema()方法时创建了对象,因此在此之后无法动态修改值。这意味着enum接受的值一旦设置就无法更改。

最好的方法是将所有值添加到单个数组中,然后将其设置为枚举值,并在其他位置执行子类别限制。