我正在尝试连接到 Mongo Db 我的代码如下;
import express from "express";
import dotenv from "dotenv";
import mongoose from "mongoose";
import cors from "cors";
import cookieParser from "cookie-parser";
dotenv.config();
const app = express();
const port = process.env.PORT || 8000;
// //for testing
// app.get("/", (req, res) => {
// res.send("api is working");
// });
//database connect
// tourbooking tour1992
mongoose.set("strictQuery", false);
const connect = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("MongoDB database connected");
} catch (err) {
console.log("MongoDB database connection failed");
}
};
// middleware
app.use(express.json());
app.use(cors());
app.use(cookieParser());
app.listen(port, () => {
console.log("server listening on port", port);
});
输出如下;
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
server listening on port 4000
但未连接到服务器消息未显示,并且控制台有以下错误:
请帮忙解决上述代码问题?再说一遍,我在编码方面还是个小孩,非常感谢您提前提供的帮助
您应该调用
connect
方法并声明路线:
// //for testing
app.get("/", (req, res) => {
res.send("api is working");
});
// middleware
app.use(express.json());
app.use(cors());
app.use(cookieParser());
mongoose.set("strictQuery", false);
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log("MongoDB database connected");
app.listen(port, () => {
console.log("server listening on port", port);
});
}).catch(err => {
console.log("MongoDB database connection failed");
});