Skip to content

Commit

Permalink
Merge pull request #13968 from Automattic/vkarpov15/gh-13956
Browse files Browse the repository at this point in the history
fix(document): avoid triggering setter when initializing `Model.prototype.collection` to allow defining `collection` as a schema path name
  • Loading branch information
vkarpov15 committed Oct 13, 2023
2 parents e1d3bfa + 157823c commit a72c023
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 @@ -4764,8 +4764,6 @@ Model.compile = function compile(name, schema, collectionName, connection, base)

schema._preCompile();

model.prototype.$__setSchema(schema);

const _userProvidedOptions = schema._userProvidedOptions || {};

const collectionOptions = {
Expand All @@ -4778,13 +4776,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 @@ -4793,8 +4794,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 @@ -12608,6 +12608,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 a72c023

Please sign in to comment.