Mongoose连接类型错误

zrfyljdw  于 2023-08-06  发布在  Go
关注(0)|答案(1)|浏览(133)

我是Mongodb/Mongoose的新手。
我正在开发MERN堆栈应用程序。一切工作除了 Mongoose 连接。我一直得到错误:“类型错误:无法读取Object...server.js中undefined的属性(阅读'connect')“
看起来调用mongoose上的.connect方法是错误的来源。如果我能找到解决这个问题的办法,我会很高兴的。
我的server.js代码是:

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}.`);
});

字符串
我正在尝试将MERN应用程序连接到mongoose db

编辑:

下面是models文件夹中的index.js:

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;

avwztpqn

avwztpqn1#

下面是models文件夹中的index.js:

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;

字符串

相关问题