无法修复猫鼬覆盖模型错误

Can't fix mongoose overwrite model error

本文关键字:覆盖 模型 错误      更新时间:2023-09-26

我正在使用角度全栈生成器,并且我添加了一个模特人。当我尝试在种子.js文件中要求人员模型时,出现此错误。

    /Users/dev/wishlist/node_modules/mongoose/lib/index.js:334
      throw new mongoose.Error.OverwriteModelError(name);
            ^
OverwriteModelError: Cannot overwrite `Person` model once compiled.
    at Mongoose.model (/Users/dev/wishlist/node_modules/mongoose/lib/index.js:334:13)
    at Object.<anonymous> (/Users/dev/wishlist/server/api/wishList/person.model.js:11:27)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/Users/dev/wishlist/server/api/wishList/wishList.controller.js:4:14)
    at Module._compile (module.js:456:26)

我遵循了生成器附带的"事物"模型相同的结构。还进行了搜索,以及 Person 在代码库中的位置,并且仅在 person.model 中.js 和控制器中。

人物模型.js:

'use strict';
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;
var PersonSchema = new Schema({
  name: String,
  quote: String
});
module.exports = mongoose.model('Person', PersonSchema);

wishlist.controller.js:

'use strict';
var _ = require('lodash');
var Person = require('./person.model');
// Get all the People that have wish lists
exports.getPeople = function(req, res) {
  Person.find(function (err, people) {
    if(err) { return handleError(res, err); }
    return res.json(200, people);
  });
};
function handleError(res, err) {
  return res.send(500, err);
}

我错过了什么?

据我了解,从您发布的信息中,该问题似乎是由以下几行引起的:

在对象。(/Users/dev/wishlist/server/api/wishList/person.model.js:11:27)

module.exports = mongoose.model('Person', PersonSchema);

在对象。(/Users/dev/wishlist/server/api/wishList/wishList.controller.js:4:14)

var Person = require('./person.model');

此错误通常来自猫鼬模型之间的不匹配。

在路上的某个地方,您已使用不同的名称定义了此模型,但具有相同的架构。

为了查看这是否是导致错误的原因,请在需要mongoose后立即将此代码添加到person.model.js中:

'use strict';
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;
mongoose.models = {};
mongoose.modelSchemas = {};

这将清除您的猫鼬数据并清空所有现有模型和架构。

我在以下链接中找到了上述信息。

我还发现了一些额外的讨论,可以解决这个问题 这里 和 这里.

几周

前我也遇到了同样的错误。在尝试了一些事情之后,我得出了一个简单的修复方法:

只是尝试以这种方式导出人物模型 -

module.exports.PersonModel = mongoose.model('Person', PersonSchema);

而不是 - module.exports = mongoose.model('Person', PersonSchema);

希望这有帮助!

如果您仍然收到错误,则只是导出此模型的模块中的路径。