I am new to Mongodb/mongoose.
I am developing MERN stack app. Everything works apart from mongoose connection. I keep getting the error: "TypeError: Cannot read properties of undefined (reading 'connect') at Object ....server.js "
It seems like calling the .connect method on mongoose is the source of the error. I'll be glad if I can get solution to this issue.
My server.js code is:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { default: mongoose } = require('mongoose');
const db = require("./App/models")
const app = express();
app.use(express.json());
const db = require("./App/models");
db.mongoose
.connect(db.url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Connected to the database!");
})
.catch(err => {
console.log("Cannot connect to the database!", err);
process.exit();
});
const corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true}));
app.get("/", (req, res) => {
res.json({ message: "Welcome to tutorial Application." });
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
I am trying to connect the MERN application to mongoose db
Edit:
Below is the index.js in the models folder:
const dbConfig = require("../config/db.config.js");
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const db = {}; db.mongoose = mongoose;
db.url = dbConfig.url;
db.tutorials = require("./tutorial.model.js")(mongoose);
module.exports.db;
Below is the index.js in the models folder: