Skip to content

Commit

Permalink
fix: avoid connection buffering on init if autoCreate: false
Browse files Browse the repository at this point in the history
Re: #15241
  • Loading branch information
vkarpov15 committed Feb 10, 2025
1 parent 1a2faa7 commit 14aca10
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
20 changes: 16 additions & 4 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -1103,16 +1103,28 @@ Model.init = function init() {
return results;
};
const _createCollection = async() => {
await conn._waitForConnect();
const autoCreate = utils.getOption(
let autoCreate = utils.getOption(
'autoCreate',
this.schema.options,
conn.config,
conn.base.options
conn.config
// No base.options here because we don't want to take the base value if the connection hasn't
// set it yet
);
if (autoCreate == null) {
// `autoCreate` may later be set when the connection is opened, so wait for connect before checking
await conn._waitForConnect();
autoCreate = utils.getOption(
'autoCreate',
this.schema.options,
conn.config,
conn.base.options
);
}

if (!autoCreate) {
return;
}

return await this.createCollection();
};

Expand Down
13 changes: 13 additions & 0 deletions test/connection.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1637,6 +1637,19 @@ describe('connections:', function() {
assert.ok(!res.map(c => c.name).includes('gh12940_Conn'));
});

it('does not wait for buffering if autoCreate: false (gh-15241)', async function() {
const m = new mongoose.Mongoose();
m.set('bufferTimeoutMS', 100);

const schema = new Schema({ name: String }, {
autoCreate: false
});
const Model = m.model('gh15241_Conn', schema);

// Without gh-15241 changes, this would buffer and fail even though `autoCreate: false`
await Model.init();
});

it('should not create default connection with createInitialConnection = false (gh-12965)', function() {
const m = new mongoose.Mongoose({
createInitialConnection: false
Expand Down

0 comments on commit 14aca10

Please sign in to comment.