**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
As the accepted answer is quite weird and not resolve the root cause. I write my 2 cents here.
Node separates code by modules by default, which mean your app's code and your gaming's route code won't interfere/know each other.
To make it work, you import or require other modules into the one you want to use.
In your case, you need to import User into the gaming route.
instead of
const User = mongoose.model('gaming', mySchema);
Try using
const User = (module.exports = mongoose.model('gaming', mySchema));;