如何摆脱错误:“OverwriteModelError:不能覆盖`一旦编译未定义的模型。”?

我有一个更新MongoDB中任何集合文档的常用方法?

以下代码的文件名为Deleter.js

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

并在我的主文件app.js中调用如下:

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

我收到以下错误:

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

我只有第二个方法调用。请让我知道如果有任何人有一些解决scheme。

我想你已经在相同的模式两次实例化mongoose.Model() 。 您应该只创build一个模型一次,并且有一个全局对象来在需要的时候抓住它们

我假设你在目录$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); 

在你的app.js

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

而当你需要它

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

我设法解决这个问题:

 var Admin; if (mongoose.models.Admin) { Admin = mongoose.model('Admin'); } else { Admin = mongoose.model('Admin', adminSchema); } module.exports = Admin; 

我尽量避免使用全局variables,因为一切都是通过引用的方式来实现的,而且事情可能会变得混乱。 我的解决scheme

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); } } 

我发现最好避免全球和例外的处理 –

 var mongoose = require("mongoose"); var _ = require("underscore"); var model; if (_.indexOf(mongoose.modelNames(), "Find")) { var CategorySchema = new mongoose.Schema({ name: String, subCategory: [ { categoryCode: String, subCategoryName: String, code: String } ] }, { collection: 'category' }); model = mongoose.model('Category', CategorySchema); } else { model = mongoose.model('Category'); } module.exports = model; 

其实问题不在于mongoose.model()被实例化了两次。 问题在于Schema被实例化了一次以上。 例如,如果你做了mongoose.model("Model", modelSchema) n次,并且你对Schema使用了相同的引用,这对于mongoose来说不会是个问题。 当你在同一个模型上使用另一个模式引用时,问题就来了

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

这是发生此错误的情况。

如果你看源码(mongoose/lib/index.js:360)这是检查

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