我有一个关于“拓扑已关闭”的错误,无法连接到 mongodb,并且还出现此错误 MongooseServerSelectionError。请检查下面的错误日志。
我尝试了许多来自其他来源的配置,但没有成功。希望有人已经知道/能够解决这个问题。
Error: MongooseServerSelectionError: connect ECONNREFUSED 0.0.0.0:27017/home/app/node_modules/mongodb/lib/sdam/topology.js:225
drainWaitQueue(this[kWaitQueue], new error_1.MongoTopologyClosedError());
MongoTopologyClosedError: Topology is closed
at Topology.close (/home/app/node_modules/mongodb/lib/sdam/topology.js:225:42)
at Topology._connect (/home/app/node_modules/mongodb/lib/sdam/topology.js:211:18)
at async Topology.connect (/home/app/node_modules/mongodb/lib/sdam/topology.js:158:13)
at async topologyConnect (/home/app/node_modules/mongodb/lib/mongo_client.js:204:17)
at async MongoClient._connect (/home/app/node_modules/mongodb/lib/mongo_client.js:217:13)
at async MongoClient.connect (/home/app/node_modules/mongodb/lib/mongo_client.js:142:13)
at async NativeConnection.createClient (/home/app/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js:314:3)
at async NativeConnection.openUri (/home/app/node_modules/mongoose/lib/connection.js:846:5) {
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v19.9.0
我在这些链接上尝试了很多配置,但没有成功。
使用 Docker 运行 MongoDB“首次连接时无法连接到服务器 [localhost:27017]”
MongoError:连接ECONNREFUSED 127.0.0.1:27017
我的dockerfile
FROM node:19-alpine
ENV MONGO_DB_USERNAME=admin \
MONGO_DB_PWD=password
RUN mkdir -p /home/app
COPY . /home/app
WORKDIR /home/app
RUN npm install
RUN npm run build
CMD ["node", "./dist/index.js"]
我的 mongodb 连接
import mongoose from "mongoose";
//localhost ~~ 127.0.0.1 ~~ 0.0.0.0 won't work
// tried this "mongodb" or "mongo-express" from docker-compose file still not working
export const mongooDbConnect = () => {
mongoose
.connect("mongodb://admin:[email protected]:27017", {
dbName: "car_be",
})
.then(() =>
console.log(
"****************\n\n Connected to the MONGODB database \n\n****************"
)
)
.catch((err) => console.log(`Error: ${err}`));
return mongoose;
};
我的 docker-compose 文件
version: "3"
services:
mongodb:
image: mongo
ports:
- 27017:27017
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=password
volumes:
- mongo-data:/data/db
mongo-express:
image: mongo-express
restart: always
ports:
- 8080:8081
environment:
- ME_CONFIG_MONGODB_ADMINUSERNAME=admin
- ME_CONFIG_MONGODB_ADMINPASSWORD=password
- ME_CONFIG_MONGODB_SERVER=mongodb
volumes:
mongo-data:
driver: local