Skip to content

Commit

Permalink
fix(connection): pull correct autoCreate value from Mongoose global…
Browse files Browse the repository at this point in the history
… when creating new model before calling `connect()`

Fix #10091
  • Loading branch information
vkarpov15 committed Apr 16, 2021
1 parent 7b2b1bf commit dad2e20
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 4 deletions.
9 changes: 7 additions & 2 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ function Connection(base) {
this.base = base;
this.collections = {};
this.models = {};
this.config = { autoIndex: true };
this.config = {};
this.replica = false;
this.options = null;
this.otherDbs = []; // FIXME: To be replaced with relatedDbs
Expand Down Expand Up @@ -727,6 +727,7 @@ Connection.prototype.openUri = function(uri, options, callback) {

if (options) {
options = utils.clone(options);

const autoIndex = options.config && options.config.autoIndex != null ?
options.config.autoIndex :
options.autoIndex;
Expand Down Expand Up @@ -1116,7 +1117,11 @@ Connection.prototype.onClose = function(force) {
*/

Connection.prototype.collection = function(name, options) {
options = options ? utils.clone(options) : {};
const defaultOptions = {
autoIndex: this.config.autoIndex != null ? this.config.autoIndex : this.base.options.autoIndex,
autoCreate: this.config.autoCreate != null ? this.config.autoCreate : this.base.options.autoCreate
};
options = Object.assign({}, defaultOptions, options ? utils.clone(options) : {});
options.$wasForceClosed = this.$wasForceClosed;
if (!(name in this.collections)) {
this.collections[name] = new Collection(name, this, options);
Expand Down
3 changes: 2 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ function Mongoose(options) {
this.events = new EventEmitter();
// default global options
this.options = Object.assign({
pluralization: true
pluralization: true,
autoIndex: true
}, options);
const conn = this.createConnection(); // default connection
conn.models = this.models;
Expand Down
4 changes: 3 additions & 1 deletion lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -4765,9 +4765,11 @@ Model.compile = function compile(name, schema, collectionName, connection, base)
const collectionOptions = {
schemaUserProvidedOptions: _userProvidedOptions,
capped: schema.options.capped,
autoCreate: schema.options.autoCreate,
Promise: model.base.Promise
};
if (schema.options.autoCreate !== void 0) {
collectionOptions.autoCreate = schema.options.autoCreate;
}

model.prototype.collection = connection.collection(
collectionName,
Expand Down

0 comments on commit dad2e20

Please sign in to comment.