Cannot overwrite `User` model once compiled. When resolved i get 'User' Undefined

Viewed 95

I'm currently working on the backend of a shopping website, while working on my post functions. I get this error "OverwriteModelError: Cannot overwrite User model once compiled." Everything works fine until when i go for the buy character where it needs a search query for both the User and Character and pushing the character into the array ownedCharacter in the User model. when i remove the const User = require('../Model/User'); and test the function buy character in postman it says that the User is Undefined.

Here's the code for the model

const mongoose = require('mongoose');



const UserSchema = new mongoose.Schema({
    username:{
        type: String,
        required : true
    },
    email:{
        type: String,
        required: true
    },
    password:{
        type: String,
        required: true,
        min: 8
    },
    status:{
        type:Boolean,
        default:false
    },
    points:{
        type:Number,
        default: 0
    },
    rank:{
        type:String,
        default:"unranked"
    },
    avatar:{
        type:String,
        default:""
    },
    level:{
        type:Number,
        default:0
    },
    experience:{
        type:Number,
        default:0
    },
    registrationDate:{
        type:Date,
        default:Date.now()
    },
    gold:{
        type:Number,
        default:0
    },
    gems:{
        type:Number,
        default:0
    },
    ownedCharacter:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:"Character",
    }],
  

    
},{timestamps:true});

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

Here's the code for the app.js

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const bodyParser = require("body-parser");


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
  }));
app.use(express.static('uploads'));
//Import Routes
const authRoute = require ('./Route/Auth'); 
const authAdminRoute = require ('./Route/Admin_Auth'); 
const shopRoute = require('./Route/Shop');


dotenv.config();

//Connection to DataBase
mongoose.connect(
    process.env.DB_CONNECT,
    {useNewUrlParser: true, useUnifiedTopology: true},
    ()=>console.log('connected to database')
);

//MiddleWares
app.use(express.json());



//Route MiddleWares 
app.use('/api/user', authRoute);
app.use('/api/admin', authAdminRoute);
app.use('/api/shop',shopRoute);


//Server Listener
app.listen(27017, ()=> console.log("Server Running"));


and here's the shop route

const router = require('express').Router();
const User = require('../Model/User');
const Character = require('../Model/Character');
const Skin = require('../Model/Skin');




//admin add character
router.post('/addCharacter', async (req, res) =>{
    
    const character = new Character({ 
    name:req.body.name,
    price:req.body.price,
    story:req.body.story,
    ability:{
        abilityName:req.body.abilityName,
        cooldown:req.body.cooldown,
        description:req.body.description
    },
  });
    try {
        const savedCharacter = await character.save();
    res.json({savedCharacter});
    console.log(character);
    } catch (error) {
        
    }    
});

//add Skin
router.post('/addSkin/:characterId', async (req, res) =>{
    
    const skin = new Skin({ 
    name:req.body.name,
    price:req.body.price,
    description:req.body.description,
    characterId: req.params.characterId
    
  });
    try {
        const savedSkin = await skin.save();
    res.json({skin});
    console.log(skin);
    } catch (error) {
        
    }
    
});

 //add Monsters

 
 router.post('/addMonster/', async (req, res) =>{
    
    const mosnter = new Monster({ 
    name:req.body.name,
    price:req.body.price,
    description:req.body.description,
    
  });
    try {
        const savedMonster = await monster.save();
    res.json({monster});
    console.log(monster);
    } catch (error) {
        
    }
    
});



//add Traps

router.post('/addTrap', async (req, res) =>{
    
    const trap = new Trap({ 
    name:req.body.name,
    price:req.body.price,
    description:req.body.description,
    
    
  });
    try {
        const savedTrap = await trap.save();
    res.json({trap});
    console.log(trap);
    } catch (error) {
        
    }
    
});





//buy a Character
router.post('/buyCharacter/:characterId/:userId',async(req,res)=>{
    try {
        const user = await User.findOne({_id:req.params.userId});
        console.log("user:"+user);
        const boughtCharacter = await Character.findOne({_id:req.params.characterId});
        user.ownedCharacter.push(boughtCharacter);
        user.save();
        res.json(boughtCharacter);
        console.log(boughtCharacter);
    } catch (error) {
        console.log(error.message);
    }
    
    });






module.exports = router;

2 Answers

Is the casing correctly matched between your require statements and the file names? If the filename is actually /Model/user.js, it could throw this error.

The error message is telling you that somehow, you are declaring a model named User more than once. Unless you are explicitly doing so again in another file, you're best bet is that the User.js file is being loaded twice. There are a few reasons why that can happen, but the most likely cause is that you are importing the ../Model/User.js file in multiple places, but your casing is inconsistent.

When Node loads an import, it caches it using the resolved filename you pass to require()... and it does so in a case-sensitive manner. What that means is that if you have require(../Model/user) in one file and require(../Model/User) in another, Node will load the same file twice, thus executing the file twice, thus attempting to set a model named User on the shared mongoose instance twice, and thus giving you the OverwriteModelError you are experiencing.

I'd do a find in your IDE and look at everywhere you are requiring that model.

Related