Skip to content

Commit

Permalink
fix(document): avoid triggering setter when initializing `Model.proto…
Browse files Browse the repository at this point in the history
…type.collection` to allow defining `collection` as a schema path name

Fix #13956
  • Loading branch information
vkarpov15 committed Oct 11, 2023
1 parent a1d2bf9 commit 157823c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
15 changes: 8 additions & 7 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -4759,8 +4759,6 @@ Model.compile = function compile(name, schema, collectionName, connection, base)

schema._preCompile();

model.prototype.$__setSchema(schema);

const _userProvidedOptions = schema._userProvidedOptions || {};

const collectionOptions = {
Expand All @@ -4773,13 +4771,16 @@ Model.compile = function compile(name, schema, collectionName, connection, base)
collectionOptions.autoCreate = schema.options.autoCreate;
}

model.prototype.collection = connection.collection(
const collection = connection.collection(
collectionName,
collectionOptions
);

model.prototype.$collection = model.prototype.collection;
model.prototype[modelCollectionSymbol] = model.prototype.collection;
model.prototype.collection = collection;
model.prototype.$collection = collection;
model.prototype[modelCollectionSymbol] = collection;

model.prototype.$__setSchema(schema);

// apply methods and statics
applyMethods(model, schema);
Expand All @@ -4788,8 +4789,8 @@ Model.compile = function compile(name, schema, collectionName, connection, base)
applyStaticHooks(model, schema.s.hooks, schema.statics);

model.schema = model.prototype.$__schema;
model.collection = model.prototype.collection;
model.$__collection = model.collection;
model.collection = collection;
model.$__collection = collection;

// Create custom query constructor
model.Query = function() {
Expand Down
12 changes: 12 additions & 0 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12600,6 +12600,18 @@ describe('document', function() {
['I am NumberTyped', 'I am StringTyped']
);
});

it('can use `collection` as schema name (gh-13956)', async function() {
const schema = new mongoose.Schema({ name: String, collection: String });
const Test = db.model('Test', schema);

const doc = await Test.create({ name: 'foo', collection: 'bar' });
assert.strictEqual(doc.collection, 'bar');
doc.collection = 'baz';
await doc.save();
const { collection } = await Test.findById(doc);
assert.strictEqual(collection, 'baz');
});
});

describe('Check if instance function that is supplied in schema option is availabe', function() {
Expand Down

0 comments on commit 157823c

Please sign in to comment.