簡體   English   中英

無法修復貓鼬覆蓋模型錯誤

[英]Can't fix mongoose overwrite model error

我正在使用 angular-fullstack 生成器,並且我添加了一個模型人。 當我嘗試在 seed.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 和控制器中。

person.model.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 模型之間的不匹配。

沿着這條路的某個地方,您以不同的名稱定義了此模型,但使用了相同的 Schema。

為了看看這是導致你錯誤的東西,在添加此代碼person.model.js你需要之后mongoose

'use strict';

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

mongoose.models = {};
mongoose.modelSchemas = {};

這將清除您的貓鼬數據並清空所有現有模型和模式。

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

我還發現了一些解決此問題的其他討論HEREHERE

幾周前我也遇到了同樣的錯誤。 在嘗試了幾件事之后,我得出了一個簡單的解決方法:

嘗試以這種方式導出人物模型 -

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

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

希望這可以幫助 !

如果您仍然收到錯誤,只是您正在導出此模型的模塊中的路徑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM