简体   繁体   中英

OverwriteModelError: Cannot overwrite `user` model once compiled

I am facing this issue. I looked online for hours to find out what the problem is before posting here. I keep getting this error OverwriteModelError: Cannot overwrite ``user`` model once compiled. after sending a post request via postman and I can't find out what's going on. could you help me find out what's going on? thank you so much in advance!

server.js

const express = require("express");
const app = express();
const user = require("./routes/user");
const connectDB = require("./config/db");

connectDB();
app.use(express.json({extended: false}));
app.get("/", (req, res) => {
  res.send("welcome to our api");
});
app.use("/user", user);

const PORT = 3000 || process.env.PORT;
app.listen(PORT, () => {
  console.log(`PORT ${PORT} listening and refeshing...`);
});

db.js

const mongoose = require("mongoose");
const connectDB = () =>
  mongoose
    .connect(
      "some database",
      {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      }
    )
    .then(
      () => {
        console.log("mongoDB conneted");
      },
      (err) => {
        console.log(err);
      }
    );
module.exports = connectDB;

user.js

const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const {body, validationResult} = require("express-validator");
router.get("/", (req, res) => {
  res.send("hello");
});

router.post(
  "/",
  [
    // password must be at least 5 chars long
    body("email").isEmail(),
    body("password").not().isEmpty(),
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty) {
      return res.status(400).json({errors: errors.array()});
    }

    try {
      const UsersSchema = mongoose.Schema({
        email: {type: String, required: true},
        password: {type: String, required: true},
      });

      var users = mongoose.model("user", UsersSchema);

      var user = new users({
        email: req.body.email,
        password: req.body.password,
      });

      const salt = await bcrypt.genSalt(10);
      user.password = await bcrypt.hash(req.body.password, salt);
      user.save((err, user1) => {
        if (err) {
          console.log("error posing user");
          throw err;
        }
      });
      console.log(user.id);
      const payload = {
        user: {
          id: user.id,
        },
      };
    } catch (error) {
      console.log(error);
      res.status(400);
    }
  }
);
module.exports = router;

Every time the route runs it tries to create a schema which is already created.Mongoose create the collection with the first argument user by converting it to plural ie users .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM