升级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
相关产品推荐
相关产品推荐

