Home > front end >  Why are db collections created for Mongoose 6 subdocs?
Why are db collections created for Mongoose 6 subdocs?

Time:08-05

I'm looking at upgrading my projects mongoose version from 5.10.19 to latest (6.5.1). I'm noticing that I have a lot more collections in my database than I did before. I made a simple example to test this out and when I run it on mongoose 5, I only see the collection "mains" but mongoose 6 creates "mains" and "subs". I'd expect that the subdocument models would not have their own collection like mongoose 5 behaves.

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);
  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();
  });

Is there a mongoose setting I'm missing that's causing this to happen?

Also, on Node 12.20.12.

CodePudding user response:

It's probably because of this change:

autoCreate is true by default unless readPreference is secondary or secondaryPreferred, which means Mongoose will attempt to create every model's underlying collection before creating indexes.

So turning off autoCreate (and possibly autoIndex) on subSchema should fix it. Alternatively, just don't create a model of it (only the schema).

  • Related