Amo*_*rni 17 mongoose mongodb node.js
我有一个更新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)
我只接受第二次方法通话.如果有任何人有解决方案,请告诉我.
小智 41
我设法像这样解决了这个问题:
var Admin;
if (mongoose.models.Admin) {
  Admin = mongoose.model('Admin');
} else {
  Admin = mongoose.model('Admin', adminSchema);
}
module.exports = Admin;
小智 26
我认为你已经mongoose.Model()在同一个模式上实例化了两次.您应该只创建一次每个模型并拥有一个全局对象,以便在需要时获取它们
我假设您在目录下的不同文件中声明了不同的模型 $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(.....
小智 9
我尽可能地避免使用全局变量,因为一切都是通过引用,事情可能会变得混乱.我的解决方案
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);
    }
  }
小智 5
实际上问题不在于mongoose.model()实例化两次。问题是 被Schema实例化多次。例如,如果您执行mongoose.model("Model", modelSchema)n 次并且使用对架构的相同引用,这对于 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);
}