How do you remove a model from mongoose?

≯℡__Kan透↙ 提交于 2019-11-29 03:51:00

try this

delete mongoose.connection.models['Book'];

and then re-register/re-initialize it . it will work fine

EmptyArsenal

It appears that you'd have to overwrite some of the source code in order to be able to remove a model an add a new one since Mongoose makes sure that a model doesn't exist before it's willing to create a new one, which may or may not be more than you care to do:

if (this.models[name] && !collection) {
    // model exists but we are not subclassing with custom collection
    if (schema instanceof Schema && schema != this.models[name].schema) {
      throw new MongooseError.OverwriteModelError(name);
    }
    return this.models[name];
}

Line 587 https://github.com/LearnBoost/mongoose/blob/master/lib/connection.js

Question Author's Update:

Thanks to this answer I discovered that you can access the models defined on the connection through connection.models. In my scenario I was testing a mongoose plugin with Mocha and and I wanted to clear the models between each unit test.

afterEach(function () {
    mongoose.connection.models = {};
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!