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

升级Mongoose 6后为何子文档会生成独立集合?

问题解决:Mongoose 6中子文档Schema生成独立集合的问题

核心原因是你调用了model('Sub', subSchema)注册了Sub模型——在Mongoose 6中,只要注册模型,即使未直接用该模型执行数据库操作,MongoDB也会自动创建对应集合;而Mongoose 5仅在模型实际执行读写操作时才会创建集合。

解决方案1:移除不必要的子模型注册

如果subSchema仅作为Main模型的子文档使用,不需要独立集合,直接删除model('Sub', subSchema)这一行即可:

import { connect, model, Schema } from 'mongoose';

const mongoUrl = 'mongodb://localhost:27017/test';

(async () => {
  const subSchema: Schema = new Schema({ color: String, yes: Boolean });
  const mainSchema: Schema = new Schema({ name: String, sub: subSchema });

  const MainModel = model('Main', mainSchema);
  // 移除Sub模型的注册
  // model('Sub', subSchema);

  await connect(mongoUrl, { ssl: true, sslValidate: false });
  console.log(`Successfully connected to mongodb: \"${mongoUrl}\"`);

  await MainModel.create({ name: 'One', sub: { color: 'Yellow', yes: true } });
})()
  .then(() => {
    console.log('\nSuccess');
    process.exit();
  })
  .catch(() => {
    console.log('\nFailure');
    process.exit();
  });

解决方案2:禁用模型自动创建集合(如需保留Sub模型注册)

如果确实需要注册Sub模型但不想自动生成集合,可以在定义Schema时添加autoCreate: false配置:

const subSchema: Schema = new Schema({ color: String, yes: Boolean }, { autoCreate: false });
model('Sub', subSchema);

这样即使注册了Sub模型,Mongoose也不会自动创建集合,只有当你主动使用Sub模型执行操作时才会生成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 07:48:15