Skip to content

Commit

Permalink
Merge pull request #14306 from Automattic/vkarpov15/gh-14296
Browse files Browse the repository at this point in the history
feat(model): add `recompileSchema()` function to models to allow applying schema changes after compiling
  • Loading branch information
vkarpov15 committed Feb 6, 2024
2 parents 33c2f4f + e332479 commit f696543
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
29 changes: 29 additions & 0 deletions lib/model.js
Expand Up @@ -4861,6 +4861,35 @@ Model.__subclass = function subclass(conn, schema, collection) {
return Model;
};

/**
* Apply changes made to this model's schema after this model was compiled.
* By default, adding virtuals and other properties to a schema after the model is compiled does nothing.
* Call this function to apply virtuals and properties that were added later.
*
* #### Example:
*
* const schema = new mongoose.Schema({ field: String });
* const TestModel = mongoose.model('Test', schema);
* TestModel.schema.virtual('myVirtual').get(function() {
* return this.field + ' from myVirtual';
* });
* const doc = new TestModel({ field: 'Hello' });
* doc.myVirtual; // undefined
*
* TestModel.recompileSchema();
* doc.myVirtual; // 'Hello from myVirtual'
*
* @return {undefined}
* @api public
* @memberOf Model
* @static
* @method recompileSchema
*/

Model.recompileSchema = function recompileSchema() {
this.prototype.$__setSchema(this.schema);
};

/**
* Helper for console.log. Given a model named 'MyModel', returns the string
* `'Model { MyModel }'`.
Expand Down
13 changes: 13 additions & 0 deletions test/model.test.js
Expand Up @@ -7302,6 +7302,19 @@ describe('Model', function() {
/First argument to `Model` constructor must be an object/
);
});

it('supports recompiling model with new schema additions (gh-14296)', function() {
const schema = new mongoose.Schema({ field: String });
const TestModel = db.model('Test', schema);
TestModel.schema.virtual('myVirtual').get(function() {
return this.field + ' from myVirtual';
});
const doc = new TestModel({ field: 'Hello' });
assert.strictEqual(doc.myVirtual, undefined);

TestModel.recompileSchema();
assert.equal(doc.myVirtual, 'Hello from myVirtual');
});
});


Expand Down
3 changes: 3 additions & 0 deletions types/models.d.ts
Expand Up @@ -711,6 +711,9 @@ declare module 'mongoose' {
options?: (mongodb.ReplaceOptions & MongooseQueryOptions<TRawDocType>) | null
): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, TRawDocType, 'replaceOne'>;

/** Apply changes made to this model's schema after this model was compiled. */
recompileSchema(): void;

/** Schema the model uses. */
schema: Schema<TRawDocType>;

Expand Down

0 comments on commit f696543

Please sign in to comment.