node.js 如何摆脱错误:“OverwriteModelError:一旦编译就无法覆盖`undefined`模型。”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14641834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:04:47  来源:igfitidea点击:

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

node.jsmongodbmongoose

提问by Amol M Kulkarni

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

我有更新 MongoDB 中任何集合的文档的通用方法吗?

The following code is in file name Deleter.js

以下代码在文件名Deleter.js 中

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

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

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

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

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.

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

回答by paulbjensen

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;

回答by hotienvu

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

我认为您已经mongoose.Model()在同一个架构上实例化了两次。您应该只创建每个模型一次,并在需要时使用全局对象来获取它们

I assume you declare different models in different files under directory $YOURAPP/models/

我假设您在目录下的不同文件中声明不同的模型 $YOURAPP/models/

$YOURAPPDIR/models/
 - index.js
 - A.js
 - B.js

index.js

索引.js

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

A.js

js

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

B.js

js

module.exports = mongoose.model('B', BSchema);

in your app.js

在你的 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(.....

回答by Amol M Kulkarni

I try to avoid globals as much as possible, since everything is by reference, and things can get messy. My solution

我尽量避免使用全局变量,因为一切都是参考,事情可能会变得混乱。我的解决方案

model.js

模型.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);
    }
  }

回答by Kavi

I found it better to avoid global and exception handing-

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

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;

回答by Nikolay Stavrev

Actually the problem is not that mongoose.model()is instantiated twice. The problem is that the Schemais instantiated more than one time. For example if you do mongoose.model("Model", modelSchema)n times and you are using the same reference to the Schema this would not be a problem for mongoose. The problem comes when you use another reference of schema on the same model i.e

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

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

This is the situation when this error occurs.

这是发生此错误时的情况。

If you look at the source (mongoose/lib/index.js:360)this is the check

如果你查看源代码,(mongoose/lib/index.js:360)这是支票

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

回答by DavidLee

This is because require one Model in two paths.

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

// Comment Model file

// 注释模型文件

var mongoose = require('mongoose')
var Schema = mongoose.Schema

var CommentSchema = Schema({
  text: String,
  author: String
})

module.exports = mongoose.model('Comment', CommentSchema)

// Seed file

// 种子文件

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

// index file

// 索引文件

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

Now you will get throw new mongoose.Error.OverwriteModelError(name), Cuz you require Comment model in two different ways. Seed file var Comment = require('./models/Comment'),Index file var Comment = require('./models/comment')

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