首页 > 解决方案 > 无法使用 Nodejs 连接 Mongodb 数据库

问题描述

我正在尝试将 Mongodb 数据库与 Nodejs 连接,但它显示以下错误:

Error MongoServerSelectionError: connection <monitor> to 18.235.147.2:27017 closed
at Timeout._onTimeout (D:\Backend\NodeJs\PapersBackend\node_modules\mongodb\lib\core\sdam\topology.js:438:30)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map {
  'cluster0-shard-00-01.ef0q5.mongodb.net:27017' => [ServerDescription],
  'cluster0-shard-00-02.ef0q5.mongodb.net:27017' => [ServerDescription],
  'cluster0-shard-00-00.ef0q5.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}

我无法得到下面的确切问题是我的代码:

const express = require('express');
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;

const dburl = 'mongodb+srv://digi18:<myPasssword>@cluster0.ef0q5.mongodb.net/MyDb? 
                 retryWrites=true&w=majority';

router.use(express.json());
router.use(express.urlencoded({ extended: true }));

router.post('/register',(req,res) => {

MongoClient.connect(dburl,{ useNewUrlParser:true,useUnifiedTopology: true },(err,client) => {
            
     if(err){
         console.log("Error",err);
         }
     else{
        res.send("Connect");
        }
    });  
 });

module.exports = router;

我究竟做错了什么?

标签: node.jsmongodb

解决方案


我通过简单地将 Mongodb Atlas 仪表板中的网络访问access from anywhereadd current ip. 我不知道这是Mongodb方面的问题还是有其他出路。


推荐阅读