mongodb 编译后无法覆盖“User”模型,解析后,我得到“User”未定义

k4emjkb1  于 2023-03-29  发布在  Go
关注(0)|答案(3)|浏览(142)

我目前正在一个购物网站的后端工作,同时在我的帖子功能上工作。我得到这个错误“OverwriteModelError:Cannot overwrite User model once compiled.”一切正常,直到我去买字符,它需要一个搜索查询的用户和字符,并推动字符到数组ownedCharacter在用户模型。当我删除const User = require('../Model/User');和测试功能买字符在 Postman 它说,用户是未定义的。
下面是模型的代码

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);

下面是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"));

这是购物路线

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;
5lwkijsr

5lwkijsr1#

require语句和文件名之间的大小写是否匹配正确?如果文件名实际上是/Model/user. js,它可能会抛出此错误。

qeeaahzv

qeeaahzv2#

错误消息告诉你,不知何故,你不止一次地声明了一个名为User的模型。除非你在另一个文件中再次显式地这样做,否则你最好是User.js文件被加载了两次。发生这种情况的原因有几个,但最可能的原因是你在多个地方导入了../Model/User.js文件。但你的弹壳不一致
当Node加载一个导入时,它会使用您传递给require()的解析文件名来缓存它......并且它会以区分大小写的方式来缓存它。这意味着如果您在一个文件中有require(../Model/user),而在另一个文件中有require(../Model/User),那么Node将加载同一个文件两次,从而执行该文件两次。因此尝试在共享的mongoose示例上设置名为User的模型两次,从而得到您正在体验的OverwriteModelError
我会在你的IDE中做一个查找,看看你需要那个模型的地方。

xa9qqrwz

xa9qqrwz3#

错误显示,故障发生在与用户型号同名的其他型号中,即“User”。请检查../Model/Character../Model/Skin中的型号名称
不正确:

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

正确:

module.exports = mongoose.model("User", UserSchema);
module.exports = mongoose.model("Character", CharacterSchema);
module.exports = mongoose.model("Skin", SkinSchema);

相关问题