Skip to content

Unregister a Mongoose Model

Johnny Estilles edited this page Jan 3, 2015 · 3 revisions

Home > Knowledge Base > Unregister a Mongoose Model

How to fix 'cannot overwrite model once compiled error' message when testing Keystone

When writing tests for Keystone developers often use Mongoose models. Mongoose caches registered models for performance purposes. This, however is not ideal given the possible (and likely) collision of model names throughout our test suite. So, if two test specs create Mongoose models using the same name, the second test to run will produce a cannot overwrite model once compiled error message.

There are two possible solutions for this problem. Either we implement namespacing for models in the test suite, so that each spec has a unique model name prefix, or we can implement a post-test cleanup, in which every test unregisters any models it creates. In my tests I decided to implement the latter.

The solution I created for us is based on an solution I found in a StackOverflow question ("resetting Mongoose model cache"), which explains how to unregister a Mongoose model. The solution suggests that this can be accomplished by model form the mongoose.models object and the mongoose.modelSchemas object.

As part of the solution I created a helper function (removeModel.js) which we can all include in our tests.

For an example on how to use this helper function in your test, please see this Gist.