javascript - 如何在 JS 中编写更短的 switch 语句,同时还使用 express 和 Mongoose?
问题描述
所以情况很平静:
我需要在 3 个不同的数据库中搜索班次 ID。但这种转变也有一种类型:活动、食品和饮料或其他。
我这样做的方式,在我的 req.body 中我也有一个类型。
所以我使用 switch 语句来确定我需要搜索哪个数据库
switch(type_shift){
case("activity"):
response = await ActivityShiftDB.findByIdAndUpdate(id_shift, {$pull : {"support": user}}).exec();
break;
case("fandb"):
response = await FoodBeveragesShiftDB.findByIdAndUpdate(id_shift, {$pull : {"support": user}}).exec();
break;
case("other"):
response = await OtherShiftDB.findByIdAndUpdate(id_shift, {$pull : {"support": user}}).exec();
break;
}
这段代码感觉不干,还有其他方法吗?
解决方案
将共享部分放在switch
语句之后:
let shiftDB;
switch (type_shift) {
case "activity":
shiftDB = ActivityShiftDB;
break;
case "fandb":
shiftDB = FoodBeveragesShiftDB;
break;
case "other":
shiftDB = OtherShiftDB;
break;
default:
throw new Error("unknown type_shift");
}
response = await shiftDB.findByIdAndUpdate(id_shift, {$pull : {"support": user}}).exec();
然后,通过不使用switch
语句来简化:
const shiftDBsByType = {
"activity": ActivityShiftDB,
"fandb": FoodBeveragesShiftDB,
"other": OtherShiftDB,
}
if (!(type_shift in shiftDBsByType)) {
throw new Error("unknown type_shift");
}
response = await shiftDBsByType[type_shift].findByIdAndUpdate(id_shift, {$pull : {"support": user}}).exec();