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

MongoDB多Schema场景下Mongoose为何总是选用最后定义的Schema?

问题根源与快速解决方法

问题本质

你在search.cjs里连续三次给module.exports赋值,Node.js中module.exports是单一对象,每次赋值都会直接覆盖之前的内容。所以不管你require这个文件多少次,拿到的始终是最后一次赋值的模型——这就是为什么系统只会用最后定义的Schema。

无需重构业务代码的解决方案

不用改动现有查询逻辑,只需要修改search.cjs的导出方式,把三个模型打包成一个对象导出,避免覆盖:

修改后的search.cjs代码

const productSchema = new mongoose.Schema({
    name:{
        type: String,
        required: true
    },
    _id:{
        type: String,
        required: true
    }
});
const wishitemSchema = new mongoose.Schema({
    name:{
        type:String,
        required:true
    }
});
const cartitemSchema = new mongoose.Schema({
    _id:{
        type: String,
        required: true
    },
    name:{ // 注意:原代码里的`mame`是拼写错误,改成`name`才能正常匹配字段
        type:String,
        required:true
    }
}); 

// 把三个模型作为对象属性导出,避免覆盖
module.exports = {
    Products: mongoose.model('Products', productSchema, 'products'),
    Wishitems: mongoose.model('Wishitems', wishitemSchema, 'wishitems'),
    Cartitems: mongoose.model('Cartitems', cartitemSchema, 'cartitems')
};

对应查询代码的调整

只需要改require的方式,解构出需要的模型,后续业务逻辑完全不用动:

// 解构导出的对象,拿到三个模型
const { Products, Wishitems, Cartitems } = require('../../../Search.cjs');

router.post('/getProducts', async(req, res) =>{
    let search = await Products.find({name: {$regex: new RegExp('^'+payload+'.*', 'i')}}).exec();
    // 原有逻辑不变
})

为什么调整导出顺序能临时生效?

调整顺序后最后导出的是Products模型,所以你require文件时拿到的都是Products,调用Products.find自然能拿到正确数据。但这种方法是治标不治本——如果后续要用到Wishitems或Cartitems,同样会出现拿错模型的问题,必须通过正确的导出方式彻底解决。

内容的提问来源于stack exchange,提问作者user2280852

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 07:34:55