【问题标题】:How to get rid of Error: "OverwriteModelError: Cannot overwrite `undefined` model once compiled."?如何摆脱错误:“OverwriteModelError:一旦编译就无法覆盖`undefined`模型。”?
【发布时间】:2013-01-16 12:02:41
【问题描述】:

我有一个通用的方法来更新 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)

我只获得第二个方法调用.. 如果有人有解决方案,请告诉我。

【问题讨论】:

  • 你想用MongooseDelete做什么?为什么不直接打电话给Model_instance.remove();
  • 我只是想在我的自定义模块中使删除调用成为一种常用方法。即使我调用 MongooseDelete(/*params*/) 如果架构相同,我也会工作 n 次,当我尝试删除不同模式的文档,我收到上面的错误消息。感谢您对回答的兴趣...
  • 你不能把MongooseDelete改成只打电话给ModelObject.remove();吗?
  • 在“MongooseDelete”中,我需要“ModelObject”来调用“remove()”方法,并且应该使用特定模式创建“ModelObject”。这就是我通过值(_id 等)传递 'SchemaObject' 和 2ne 'ModelObject' 的唯一原因。
  • 你不能在两个执行文件中导入模式,当你的程序加载时它会找到两个模型并显示模型的覆盖消息。

标签: node.js mongodb mongoose


【解决方案1】:

我的解决了这个代码:

  module.exports = mongoose.models.nameOne || mongoose.model('nameOne', PostSchema);

【讨论】:

    【解决方案2】:

    这是因为在两条路径中需要一个模型。

    // 注释模型文件

    var mongoose = require('mongoose')
    var Schema = mongoose.Schema
    
    var CommentSchema = Schema({
      text: String,
      author: String
    })
    
    module.exports = mongoose.model('Comment', CommentSchema)
    

    // 种子文件

    const commentData = {
      user: "David Lee",
      text: "This is one comment"
    }
    var Comment = require('./models/Comment')
    
    module.exports = function seedDB () {
      Comment.create(commentData, function (err, comment) {
        console.log(err, commemt)
      })
    }
    

    //索引文件

    var Comment = require('./models/comment')
    var seedDB = require('./seeds')
    seedDB()
    const comment = {
      text: 'This girl is pretty!',
      author: 'David'
    }
    Comment.create(, function (err, comment) {
        console.log(err, comment)
     })
    

    现在你会得到throw new mongoose.Error.OverwriteModelError(name),因为你需要有两种不同的评论模型。种子文件var Comment = require('./models/Comment'),索引文件var Comment = require('./models/comment')

    【讨论】:

      【解决方案3】:

      其实问题不在于mongoose.model()被实例化了两次。 问题是Schema 被实例化了不止一次。 例如,如果您执行mongoose.model("Model", modelSchema) n 次并且您使用的是对 Schema 的相同引用,这对于猫鼬来说不是问题。 当您在同一模型上使用另一个架构引用时,问题就出现了,即

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

      【讨论】:

      • 很好的答案,谢谢!因此,可以通过检查 mongoose.models[name] 是否已经包含该项目来绕过对模式的调用
      【解决方案4】:

      我设法解决了这样的问题:

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

      【讨论】:

      • 谢谢。我用这个解决方案修复了我在 TypeScript 中的错误。
      • 你能解释一下它是如何工作的吗?非常感谢:)
      • 更短的代码:var Admin = mongoose.models.Admin || mongoose.model('Admin', adminSchema)
      【解决方案5】:

      我认为您已经在同一架构上实例化了两次 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(.....
      

      【讨论】:

      • 这是迄今为止更好的方案解决方案。
      • 感谢您的解释。确实很有帮助
      【解决方案6】:

      我发现最好避免全局和异常处理-

      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;
      

      【讨论】:

      • 你不是说 _.indexOf(mongoose.modelNames(), "Category") 吗?
      • 还有,@Kavi,你不是说 _.indexOf(mongoose.modelNames(), "Category") > 0 吗?
      • _.indexOf(mongoose.modelNames(), "Category")
      【解决方案7】:

      我尽量避免使用全局变量,因为所有内容都是通过引用进行的,事情可能会变得一团糟。我的解决方案

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

      【讨论】:

        猜你喜欢
        • 2019-08-31
        • 2015-04-25
        • 2017-10-04
        • 2022-08-21
        • 2020-03-06
        • 2020-11-13
        • 2019-02-28
        • 2021-05-18
        • 1970-01-01
        相关资源
        最近更新 更多