Mongoose报错:aggregate is not a function 问题求助
报错原因
你写的switch语句里,case 'cars' || 'boats'是错误写法——JavaScript会先计算'cars' || 'boats'的逻辑或结果,因为'cars'是真值,所以这个case等价于case 'cars'。只有当传入的参数是'cars'时,函数才会返回Model1;传入'boats'、'houses'或'buildings'时,没有匹配到任何case分支,函数返回undefined。undefined没有aggregate方法,自然触发TypeError。
两种解决办法
办法一:修正switch的case写法
把同一个模型对应的多个字符串拆成独立case,共用返回逻辑:
const getModelFromString = (model) => { switch(model) { case 'cars': case 'boats': return Model1; case 'houses': case 'buildings': return Model2; default: // 可选:处理未知模型的情况,避免返回undefined throw new Error(`未知模型类型:${model}`); } }
办法二:用对象映射(更简洁好维护)
直接用键值对存字符串到模型的对应关系,查询效率更高,新增模型也更方便:
const modelMap = { cars: Model1, boats: Model1, houses: Model2, buildings: Model2 }; const getModelFromString = (model) => { const targetModel = modelMap[model]; if (!targetModel) { throw new Error(`未知模型类型:${model}`); } return targetModel; }
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

