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

后端 未结 6 1768
太阳男子
太阳男子 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

    I think you have instantiated mongoose.Model() on the same schema twice. You should have created each model only once and have a global object to get a hold of them when need

    I assume you declare different models in different files under directory $YOURAPP/models/

    $YOURAPPDIR/models/
     - index.js
     - A.js
     - B.js
    

    index.js

    module.exports = function(includeFile){
        return require('./'+includeFile);
    };
    

    A.js

    module.exports = mongoose.model('A', ASchema);
    

    B.js

    module.exports = mongoose.model('B', BSchema);
    

    in your app.js

    APP.models = require('./models');  // a global object
    

    And when you need it

    // Use A
    var A = APP.models('A');
    // A.find(.....
    
    // Use B
    var B = APP.models('B');
    // B.find(.....
    

提交回复
热议问题