Skip to content

Commit

Permalink
feat(model): add recompileSchema() function to models to allow appl…
Browse files Browse the repository at this point in the history
…ying schema changes after compiling

Fix #14296
  • Loading branch information
vkarpov15 committed Jan 29, 2024
1 parent 8ef0d9a commit c480bd6
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib/model.js
Expand Up @@ -4861,6 +4861,34 @@ 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 {Model}
* @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

0 comments on commit c480bd6

Please sign in to comment.