为什么我会不断收到OverwriteModelError?

时间:2020-01-13 12:26:11

标签: node.js mongodb mongoose

启动服务器时出现以下错误:

抛出新的_mongoose.Error.OverwriteModelError(name); ^ OverwriteModelError:编译后无法覆盖User模型。 在新的OverwriteModelError(/home/pranav/exercise-tracker/mern-exercise-tracker/backend/node_modules/mongoose/lib/error/overwriteModel.js:20:11)

我的user.model.js文件

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const userSchema = new Schema(
  {
    username: {
      type: String,
      required: true,
      unique: true,
      trim: true,
      minlength: 3
    }
  },
  {
    timestamps: true
  }
);

const User = mongoose.model("User", userSchema);
module.exports = User;

我的users.js

const router = require("express").Router();
let User = require("../models/user.model");

router.route("/").get((req, res) => {
  User.find()
    .then(users => res.json(users))
    .catch(err => res.status(400).json("Error: " + err));
});

router.route("/add").post((req, res) => {
  const username = req.body.username;
  const newUser = new User({ username });

  newUser
    .save()
    .then(() => res.json("User added!"))
    .catch(err => res.status(400).json("Error: " + err));
});

module.exports = router;

server.js

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');

require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;
app.use(cors);
app.use(express.json());
const uri = process.env.ATLAS_URI;

mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;

connection.once('open', () => {
    console.log("MongoDB connection established");
})

const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');

app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);

app.listen(port, () => {
    console.log('Server is running on port : ' + port);
})

1 个答案:

答案 0 :(得分:1)

替换

const User = mongoose.model("User", userSchema);

使用

const User = mongoose.models['User'] || mongoose.model("User", userSchema);

代码运行时,user.model.js可能会再次被调用,从而调用初始定义。

请注意手术室中使用的型号 s 。该方法返回一个包含所有已定义模型的对象。也可以将其写为mongoose.models.User