简体   繁体   English

如何摆脱错误:“OverwriteModelError: Cannot overwrite `undefined` model 一旦编译。”?

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

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.我只进行第二种方法调用。如果有人有解决方案,请告诉我。

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.我认为你已经在同一个架构上实例化了mongoose.Model()两次。 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/我假设您在$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(.....

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

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;

Actually the problem is not that mongoose.model() is instantiated twice.实际上问题不在于mongoose.model()被实例化了两次。 The problem is that the Schema is instantiated more than one time.问题是Schema被实例化了Schema 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.例如,如果您执行mongoose.model("Model", modelSchema) n 次并且您使用对 Schema 的相同引用,这对mongoose.model("Model", modelSchema)来说不是问题。 The problem comes when you use another reference of schema on the same model ie当您在同一模型上使用另一个架构引用时,问题就出现了

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

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

我的解决了这个代码:

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

The problem itself is to create models with the same name, when we pass "user" as first argument we are defining only the name of the model, NOT that of the collection问题本身是创建具有相同名称的模型,当我们将“用户”作为第一个参数传递时,我们仅定义 model 的名称,而不是集合的名称

ex: mongoose.model("cadastry", cadastryUserSchema, "users")例如: mongoose.model("cadastry", cadastryUserSchema, "users")

ex: mongoose.model(nameModel, SchemaExample, NameQueyCollection)例如: mongoose.model(nameModel, SchemaExample, NameQueyCollection)

TypeScript info name: string, schema?: mongoose.Schema<...> | undefined, collection?: string | undefined TypeScript 信息name: string, schema?: mongoose.Schema<...> | undefined, collection?: string | undefined name: string, schema?: mongoose.Schema<...> | undefined, collection?: string | undefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何修复:MongooseError [OverwriteModelError]:编译后无法覆盖 `User` 模型。(MERN 堆栈)? - How to fix:MongooseError [OverwriteModelError]: Cannot overwrite `User` model once compiled.(MERN stack)? OverwriteModelError:编译后无法覆盖 `User` model。 在 Mongoose.model - OverwriteModelError: Cannot overwrite `User` model once compiled. at Mongoose.model Mongoose OverwriteModelError:编译后无法覆盖模型 - Mongoose OverwriteModelError: Cannot overwrite model once compiled OverwriteModelError:编译后无法覆盖`Product`模型 - OverwriteModelError: Cannot overwrite `Product` model once compiled 编译后无法覆盖 `User` model。 解决后我得到“用户”未定义 - Cannot overwrite `User` model once compiled. When resolved i get 'User' Undefined OverwriteModelError:编译后无法覆盖“团队”模型 - OverwriteModelError: Cannot overwrite `teams` model once compiled OverwriteModelError:编译后无法覆盖`actors`模型 - OverwriteModelError: Cannot overwrite `actors` model once compiled OverwriteModelError: 编译后无法覆盖`user` model - OverwriteModelError: Cannot overwrite `user` model once compiled 编译后无法覆盖 `User` model。 解决不了 - Cannot overwrite `User` model once compiled. cant solve it Express,猫鼬:OverwriteModelError:编译后无法覆盖“ xxxxx”模型 - Express, Mongoose : OverwriteModelError : Cannot Overwrite 'xxxxx' model once compiled
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM