0

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;
Zaid
  • 29
  • 6
  • Its something to do with your user schema can you share it? – prax Jul 24 '20 at 03:12
  • what do you mean by my user schema please? do you mean this ```const UsersSchema = mongoose.Schema({ email: {type: String, required: true}, password: {type: String, required: true}, });``` @pr1ax – Zaid Jul 24 '20 at 03:18
  • Yes ! Try creating user Schema in a different user.js file and exporting it instead in router. – prax Jul 24 '20 at 03:19
  • It seems that you are creating schema more than once. – prax Jul 24 '20 at 03:21
  • i see, but why should this make a difference? @pr1ax, oh so every time this fie is ran, it gets created again ?? – Zaid Jul 24 '20 at 03:21
  • May be but i am not sure .Here's the same error like yours:https://stackoverflow.com/questions/45150075/cannot-overwrite-users-model-once-compiled-node-js – prax Jul 24 '20 at 03:23
  • I took a look at it before posting here , but i want it to understand what's going on so i can avoid it in the future! @pr1ax – Zaid Jul 24 '20 at 03:24
  • Define `schema` into a new file and import it into your routes file – kedar sedai Jul 24 '20 at 03:29
  • @kedarsedai, i will do that but why should i do that? could explain please! thanks! – Zaid Jul 24 '20 at 03:31
  • Writing all code in same place is not a problem but it looks messy. So, separate the schema from the routes files helps to improve the readability of the code – kedar sedai Jul 24 '20 at 03:34
  • @Zaid i also think that evry time the route runs it tries to create a schema which already created .It worked for first time? – prax Jul 24 '20 at 03:51

1 Answers1

2

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 i.e. users.

prax
  • 286
  • 3
  • 10