Home > Net >  Express router is not working on mongoose. It is saying User is not defined
Express router is not working on mongoose. It is saying User is not defined

Time:04-23

**App.js Code**

const express = require("express");
const { default: mongoose } = require("mongoose");
const gaming = require("./routes/gaming");
const app = express();
app.use(express.json());

app.use("/", gaming);


const dbConnect = mongoose.connect("mongodb://localhost:27017/Gaming");

const mySchema = new mongoose.Schema({
    name: String,
    genre: String,
    games: String,
})

const User = mongoose.model('gaming', mySchema);

app.listen(8000, ()=>{
    console.log("listing at port 8000");
})



***Routes Folder Code***

const express = require("express");
let router = express.Router();

router.post("/gaming", (req,res)=>{
    const addingData = new User({
        name: req.body.name,
        genre: req.body.genre,
        games: req.body.games
    })
 addingData.save((err,result)=>{
if (err = true){
    console.log(err);
}else{
    console.log("Document dubmited successfully");
}
    })
    res.send("saved new data");
})

   module.exports = router;

I don't know why its saying User is not defined because I exported router properly into the app.js by using module.exports = router. I think the module.export is not working properly and not bringing the code to app.js file. Thanks for the help

CodePudding user response:

instead of

const User = mongoose.model('gaming', mySchema);

Try using

const User = (module.exports = mongoose.model('gaming', mySchema));;
  • Related