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

升级Mongoose 6.0.8后如何创建子模型且不自动生成对应集合

问题原因

这是Mongoose从5.x升级到6.x版本后的默认行为变更导致的:Mongoose 5.x中,仅注册模型但未主动操作时不会自动创建对应集合;6.x版本开始,只要调用mongoose.model()方法注册模型,默认就会自动生成同名集合。

解决方案

你需要拆分代码复用Schema的需求不需要通过注册子文档模型实现,有两种可行方案:

方案1(最推荐):仅导出复用子文档Schema,不注册为模型

你完全可以将子文档Schema单独拆分到独立文件做代码复用,不需要调用mongoose.model()注册,自然不会生成额外集合。

调整后的代码示例:

// 可单独拆分到 wallet-transaction.schema.js 中导出
const walletTransactionSchema = new mongoose.Schema({
        a: {type: Boolean, required: true},   
    },
    {timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}}
);

const walletSchema = new Schema({
    b: {type: Boolean, required: true},       
    transactions: [walletTransactionSchema],
});

walletSchema.index({'transactions': 1}, {sparse: true});   

module.exports.Wallet = mongoose.model('Wallet', walletSchema, 'wallets');
// 移除掉子文档模型注册的代码即可

方案2:如果确实需要注册子文档模型(需复用模型静态/实例方法),可跳过集合初始化

如果你的业务逻辑需要用到子文档模型上挂载的方法,必须注册模型的话,可以在调用mongoose.model()时传入第四个参数skipInit = true,就不会自动创建集合:

// 第四个参数设为true,跳过初始化,不会生成集合
module.exports.WalletTransaction = mongoose.model('WalletTransaction', walletTransactionSchema, null, true);

也可以在子文档Schema的配置中添加autoCreate: false,从根源禁止自动创建集合:

const walletTransactionSchema = new mongoose.Schema({
        a: {type: Boolean, required: true},   
    },
    {
        timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'},
        autoCreate: false
    }
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:06:05