gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:34:49 25 4
gpt4 key购买 nike

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

这是一个例子:

If(用户从父枚举类别数组中选择父类别家庭).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];
}
}
}

最佳答案

这在模型中是不可能的。

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

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

关于javascript - 基于同一模型中的另一个枚举数组设置枚举数组 - Mongoose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44479176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com