[英]Error: Cannot read properties of undefined (reading 'host')
I am trying to connect my application to MongoDB, but getting this error 'Error: Cannot read properties of undefined (reading 'host')'.我正在尝试将我的应用程序连接到 MongoDB,但收到此错误“错误:无法读取未定义的属性(读取“主机”)”。 Not able to figure out what might be the problem.无法弄清楚可能是什么问题。
Here is the.env file这是.env文件
PORT=5000;
MONGO_URI ='mongodb+srv://sakshi_0630:<password>@cluster0.lxchu.mongodb.net/?retryWrites=true&w=majority'
db.js file db.js 文件
const mongoose = require("mongoose");
const colors = require("colors");
const connectDB=async()=>{
try {
const conn = mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true,
});
console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline);
} catch (error) {
console.log(`Error: ${error.message}`.red.bold);
process.exit();
}
};
module.exports= connectDB;
server.js服务器.js
const { response } = require("express");
const express = require("express");
const dotenv = require("dotenv");
const { chats } = require("./data/data");
const connectDB = require("./config/db");
dotenv.config();
connectDB();
const app = express();
You need to await
the mongoose.connect()
function您需要await
mongoose.connect()
function
const connectDB = async() => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true,
});
console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline);
} catch (error) {
console.log(`Error: ${error.message}`.red.bold);
process.exit();
}
};
or use a callback function或使用回调 function
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true,
})
.then((conn) => {
console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline);
//do other things
})
.catch((error) => {
console.log(`Error: ${error.message}`.red.bold);
process.exit();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.