How to get rid of Error: “OverwriteModelError: Cannot overwrite `undefined` model once compiled.”?

后端 未结 6 1829
太阳男子
太阳男子 2021-02-05 07:34

I have a common method for updating document of any collection in MongoDB?

The following code is in file name Deleter.js

module.exports         


        
6条回答
  •  离开以前
    2021-02-05 08:17

    Actually the problem is not that mongoose.model() is instantiated twice. The problem is that the Schema is instantiated more than one time. For example if you do mongoose.model("Model", modelSchema) n times and you are using the same reference to the Schema this would not be a problem for mongoose. The problem comes when you use another reference of schema on the same model i.e

    var schema1 = new mongoose.Schema(...);
    mongoose.model("Model", schema1);
    mongoose.model("Model", schema2);
    

    This is the situation when this error occurs.

    If you look at the source (mongoose/lib/index.js:360) this is the check

    if (schema && schema.instanceOfSchema && schema !== this.models[name].schema){
        throw new mongoose.Error.OverwriteModelError(name);
    }
    

提交回复
热议问题