You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:52:08