代码之家  ›  专栏  ›  技术社区  ›  Thuan Nguyen

overwriteModelError:编译后不能覆盖“teams”模型

  •  0
  • Thuan Nguyen  · 技术社区  · 6 年前

    几个小时后。StackOverflow的研究。关于这个问题有很多文章。但我不知道我在这里出了什么问题。

    我的代码:

    模型/团队

    const mongoose = require('mongoose');
    
    const { Schema } = mongoose;
    
    const teamSchema = new Schema({
      name: { type: String, minLength: 1, required: true },
      description: { type: String },
    });
    
    mongoose.model('teams', teamSchema);
    

    型号/部门.js

    const mongoose = require('mongoose');
    
    const { Schema } = mongoose;
    
    const divisionSchema = new Schema({
      name: { type: String, minLength: 1, required: true },
      description: { type: String },
    });
    
    mongoose.model('teams', divisionSchema);
    

    我被要求进入index.js

    const express = require('express');
    const mongoose = require('mongoose');
    const bodyParser = require('body-parser');
    const keys = require('./config/keys');
    
    require('./models/Team');
    require('./models/Division');
    
    mongoose.Promise = global.Promise;
    mongoose.connect(keys.mongoURI, { useNewUrlParser: true });
    
    const app = express();
    app.use(bodyParser.json());
    
    require('./routes/teamRoutes')(app);
    
    const port = process.env.PORT || 5000;
    app.listen(port);
    

    路由/团队路由.js

    const mongoose = require('mongoose');
    
    const Team = mongoose.model('teams');
    
    module.exports = (app) => {
      app.get('/api/teams', async (req, res) => {
        const teamsList = await Team.find({});
        res.send(teamsList);
      });
    };
    

    如果我删除 require('./models/Division'); 这是有效的。为什么会这样? 如果没有,我得到错误:

    throw new mongoose.Error.OverwriteModelError(name);
      ^
    OverwriteModelError: Cannot overwrite `teams` model once compiled.
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Martial    6 年前
    mongoose.model('teams', divisionSchema);
    

    在models/division.js中,“teams”应该是“division”。