Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(connection): disable createConnection buffering if autoCreate option is changed #13007

Merged
merged 6 commits into from
Feb 21, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 29 additions & 5 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,11 @@ const modifiedPaths = require('./helpers/update/modifiedPaths');
const parallelLimit = require('./helpers/parallelLimit');
const parentPaths = require('./helpers/path/parentPaths');
const prepareDiscriminatorPipeline = require('./helpers/aggregate/prepareDiscriminatorPipeline');
const promiseOrCallback = require('./helpers/promiseOrCallback');
const pushNestedArrayPaths = require('./helpers/model/pushNestedArrayPaths');
const removeDeselectedForeignField = require('./helpers/populate/removeDeselectedForeignField');
const setDottedPath = require('./helpers/path/setDottedPath');
const STATES = require('./connectionstate');
const util = require('util');
const utils = require('./utils');

Expand Down Expand Up @@ -1354,15 +1356,37 @@ Model.init = function init(callback) {
const Promise = PromiseProvider.get();
const autoIndex = utils.getOption('autoIndex',
this.schema.options, this.db.config, this.db.base.options);
const autoCreate = utils.getOption('autoCreate',
this.schema.options, this.db.config, this.db.base.options);

const _ensureIndexes = autoIndex ?
cb => this.ensureIndexes({ _automatic: true }, cb) :
cb => cb();
const _createCollection = autoCreate ?
cb => this.createCollection({}, cb) :
cb => cb();

const model = this;
const _wrapCollHelper = function(fn) {
return function(cb) {
const conn = model.db;

return promiseOrCallback(cb, cb => {
immediate(() => {
if ((conn.readyState === STATES.connecting || conn.readyState === STATES.disconnected) && conn._shouldBufferCommands()) {
conn._queue.push({ fn: fn, ctx: conn, args: [cb] });
} else {
try {
fn.apply(conn, [cb]);
} catch (err) {
return cb(err);
}
}
});
});
};
};
const _createCollection = _wrapCollHelper(function _createCollection(cb) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For consistency, let's also delay checking autoIndex until after buffering is done. Apply similar changes to _ensureIndexes(). No need to do _wrapCollHelper on _ensureIndexes() though, since _createCollection() will already wait for buffering.

const autoCreate = utils.getOption('autoCreate',
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, let's not add a separate _wrapCollHelper() function, since that function won't be reused anywhere. Just add the if ((conn.readyState === STATES.connecting || conn.readyState === STATES.disconnected) && conn._shouldBufferCommands()) check directly into _createCollection().

model.schema.options, model.db.config, model.db.base.options);
if (autoCreate) model.createCollection({}, cb);
else cb();
});

this.$init = new Promise((resolve, reject) => {
_createCollection(error => {
Expand Down
19 changes: 19 additions & 0 deletions test/connection.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1526,4 +1526,23 @@ describe('connections:', function() {
const connectionIds = m.connections.map(c => c.id);
assert.deepEqual(connectionIds, [1, 2, 3, 4, 5]);
});

it('with autoCreate = false after schema create (gh-12940)', async function() {
const m = new mongoose.Mongoose();

const schema = new Schema({ name: String }, {
collation: { locale: 'en_US', strength: 1 },
collection: 'gh12940_Conn'
});
const Model = m.model('gh12940_Conn', schema);

await m.connect(start.uri, {
autoCreate: false
});

await Model.init();

const res = await m.connection.db.listCollections().toArray();
assert.ok(!res.map(c => c.name).includes('gh12940_Conn'));
});
});