MongooseError [OverwriteModelError]:编译后无法覆盖“Team”模型

MongooseError [OverwriteModelError]: Cannot overwrite `Team` model once compiled

我正在从 React 客户端调用 node.js express api。

当我从客户端拨打电话时,这是我的要求:

const response = await axios({
            method: 'post',
            url: 'http://localhost:3000/api/users/forgotPassword',
            data: {email: email},
            headers: {
              'X-Requested-With': 'XMLHttpRequest',
            }
          }
        );

这是 express 中的端点:

adminUserRoutes.post('/forgotPassword', (req, res) => {
  console.log('it connected')
  if (req.body.email === '') {
    res.status(400).send('email required');
  }
  console.log(req.body.email)
  console.log(req.body)
  User.findOne({email: req.body.email}, (err, user) => {
    console.log('and here')
    if(user){
      const token = crypto.randomBytes(20).toString('hex');
      console.log('use',user)
      user.resetPasswordToken = token
      user.resetPasswordExpires = Date.now() + 360000
      user.name = user.name
      user.email = user.email
      user.password = user.password
      user.admin = user.admin

      // console.log(user)

      user.save()


      const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
          user: `email`,
          pass: `password`,
        },
      });

      const mailOptions = {
        from: 'devinjjordan@gmail.com',
        to: `${user.email}`,
        subject: 'Link To Reset Password',
        text:
          'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n'
          + 'Please click on the following link, or paste this into your browser to complete the process within one hour of receiving it:\n\n'
          + `http://localhost:3000/#/newpassword/${token}\n\n`
          + 'If you did not request this, please ignore this email and your password will remain unchanged.\n',
      };

      console.log('sending mail');

      transporter.sendMail(mailOptions, (err, response) => {
        if (err) {
          console.error('there was an error: ', err);
          // res.status(200).json('there was an error: ', err);
        } else {
          console.log('here is the res: ', response);

          res.set({

              "Access-Control-Allow-Origin": "*", // Required for CORS support to work
              "Access-Control-Allow-Credentials": true // Required for cookies, authorization headers with HTTPS

          })

          res.status(200).json('recovery email sent');
        }
      });
    } else {
      console.error('email not in database');
      res.status(403).send('email not in db');
    }
  })
});

这种情况的奇怪之处在于,当我从邮递员向同一端点发出请求时,我收到了预期的响应。

但是,当我从客户端发出请求时,我收到这个错误:

MongooseError [OverwriteModelError]: Cannot overwrite `Team` model once compiled.
    at new OverwriteModelError (/Users/lukeschoenberger/Documents/Programming/news-arg/backend/node_modules/mongoose/lib/error/overwriteModel.js:20:11)
    at Mongoose.model (/Users/lukeschoenberger/Documents/Programming/news-arg/backend/node_modules/mongoose/lib/index.js:517:13)

我正在使用无服务器 labdma 并且 运行 sls 离线开始在端口 3000 上打开。

非常奇怪的是 'Team' 模型甚至没有在所讨论的 api 中提及。

编辑: 这是团队模块:

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

let Team = new Schema({
    team_name: {
        type: String
    },
    city_or_state: {
        type: String
    },
    league: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'League'
    },
    primary_color: {
        type: String
    }
}, { timestamps: true })

module.exports = mongoose.model('Team', Team)

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

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

module.exports.teamModel=mongoose.model('Team',团队);

而不是 - module.exports = mongoose.model('Team', 团队)

希望对您有所帮助!

如果您仍然遇到错误,请检查您导出此模型的模块中的路径。

事实证明这是 aws-serverless 的问题。 运行 带有此标志的 aws-serverless 解决了问题:--skipCacheInvalidation -c。更长 post 关于它:https://github.com/dherault/serverless-offline/issues/258

您在运行时多次编译您的模型。注册前检查您的模型是否已经注册:

module.exports = mongoose.models.Team || mongoose.model('Team', Team)