Amol M Kulkarni Amol M Kulkarni - 1 year ago 425
Node.js Question

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

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

The following code is in file name Deleter.js

module.exports.MongooseDelete = function (schemaObj, ModelObject);
var ModelObj = new mongoose.Model("collectionName",schemaObj);

And invoking as follows in my main file app.js:

var ModObj = mongoose.model("schemaName", schemasObj);
var Model_instance = new ModObj();
var deleter = require('Deleter.js');

I am getting following error:

OverwriteModelError: Cannot overwrite `undefined` model once compiled.
at Mongoose.model (D:\Projects\MyPrjct\node_modules\mongoose\lib\index.js:4:13)

I get on 2nd method call only..
Please let me know if any one has got some solution.

Answer Source

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/

 - index.js
 - A.js
 - B.js


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


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


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(.....
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download