How to get rid of Error: "OverwriteModelError: Cannot overwrite `undefined` model once compiled."?
I managed to resolve the problem like this:
var Admin;
if (mongoose.models.Admin) {
Admin = mongoose.model('Admin');
} else {
Admin = mongoose.model('Admin', adminSchema);
}
module.exports = Admin;
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(.....
I try to avoid globals as much as possible, since everything is by reference, and things can get messy. My solution
model.js
try {
if (mongoose.model('collectionName')) return mongoose.model('collectionName');
} catch(e) {
if (e.name === 'MissingSchemaError') {
var schema = new mongoose.Schema({ name: 'abc });
return mongoose.model('collectionName', schema);
}
}