deno icon indicating copy to clipboard operation
deno copied to clipboard

Connection timed out when using Mongoose|MongoDB with deno cli

Open Massayu opened this issue 2 years ago • 4 comments

deno-x86_64-pc-windows-msvc v1.41.1

Testing the following code using nodejs and on deno deploy works correctly:

import express    from 'express';
import mongoose   from 'mongoose';

const app = express();
await mongoose.connect("mongodb+srv://...?retryWrites=true&w=majority");
const db  = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log('Connected to MongoDB');
});

app.listen(3001, () => { console.log('starting...'); });

But when testing using deno cli it doesn't work.

I get the message on the console starting... but not the connection error: neither Connected to MongoDB

And after some time I get this error:

error: Uncaught (in promise) MongooseServerSelectionError: connection timed out
    at _handleConnectionErrors (file:///.../node_modules/.deno/[email protected]/node_modules/mongoose/lib/connection.js:875:11)

The same thing happens using mongodb instead of mongoose:

import express from 'express';
import mongodb from 'mongodb';

const app    = express();
const client = new mongodb.MongoClient("mongodb+srv://...mongodb.net/...?retryWrites=true&w=majority")
await client.connect();
const db     = client.db();

app.listen(3001, () => { console.log('starting...'); });
C:\Windows\system32>deno run --allow-all ...\index.js
Warning: Not implemented: ClientRequest.options.createConnection
error: Uncaught (in promise) MongoServerSelectionError: connection timed out
    at AbortSignal.<anonymous> (file:///...node_modules/.deno/[email protected]/node_modules/mongodb/lib/sdam/topology.js:292:34)

I'm starting the script as

deno run --allow-all ...\index.js

I also tested running it as admin, on the Mongo website I have all ip whitelisted Why do I get this error only on the CLI version?

Massayu avatar Mar 06 '24 05:03 Massayu

On my tests above i had the npm imports on deno.json now i tried with npm:

import { MongoClient } from "npm:[email protected]";

const client = new MongoClient("mongodb+srv://...");
await client.connect();
console.log("Connected successfully to server");
C:\Users\Documents\NodejsConsoleApp1>deno run --allow-all app.js
error: Uncaught (in promise) MongoServerSelectionError: connection timed out
    at Timeout._onTimeout (file:///C:/Users/Documents/NodejsConsoleApp1/node_modules/.deno/[email protected]/node_modules/mongodb/lib/sdam/topology.js:278:38)
    at cb (ext:deno_node/internal/timers.mjs:63:31)
    at Object.action (ext:deno_web/02_timers.js:154:11)
    at handleTimerMacrotask (ext:deno_web/02_timers.js:68:10)
    at eventLoopTick (ext:core/01_core.js:173:21)
Caused by: MongoNetworkTimeoutError: connection timed out
    at connectionFailureError (file:///C:/Users/Documents/NodejsConsoleApp1/node_modules/.deno/[email protected]/node_modules/mongodb/lib/cmap/connect.js:381:20)
    at TLSSocket.<anonymous> (file:///C:/Users/Documents/NodejsConsoleApp1/node_modules/.deno/[email protected]/node_modules/mongodb/lib/cmap/connect.js:285:22)
    at Object.onceWrapper (ext:deno_node/_stream.mjs:1929:32)
    at TLSSocket.emit (ext:deno_node/_stream.mjs:1854:9)
    at TLSSocket._onTimeout (node:net:848:10)
    at cb (ext:deno_node/internal/timers.mjs:63:31)
    at Object.action (ext:deno_web/02_timers.js:154:11)
    at handleTimerMacrotask (ext:deno_web/02_timers.js:68:10)
    at eventLoopTick (ext:core/01_core.js:173:21)

Massayu avatar Mar 08 '24 16:03 Massayu

@littledivy

Massayu avatar Mar 13 '24 14:03 Massayu

I've come across this issue and think the root cause is only when it's run on Windows. I didn't see this issue, wrote my own, then did 1 more search before posting and found this. So I'll just paste my issue here.

@Massayu - It might be worth updating the title to something like this for clarity, assuming you agree with my outcome Unable to connect to mongodb Atlas server using mongoose & mongodb+srv:// record on windows

Issue

When trying to connect to MongoDB Atlas using mongoose driver and a mongodb+srv:// record, the connection returns MongooseServerSelectionError: connection timed out

Quick Findings

The issue seems to only occur

  • On Windows
  • Using Deno
  • Using a mongodb+srv:// record

A related issue raised on the mongoose GitHub (linked further below) raises a question that it seems to be only for some WiFi network configs. I've tested this on a dektop PC hardwired & on a laptop with WiFI. Both have the same issue.


This for others to test/confirm

I have Windows Sandbox installed on both of my machines. That's the only think I can think of that could be messing with a network connection (massive stretch though). So can someone without it check it's still an issue.


What I've tried - DENO (no work around found)

  • URI with mongodb://
  • URI with mongodb+srv://
  • Passing it through resolve_mango_dns
    • Tried this based on #18278 - didn't help
  • Hardcoding the user/pass/server into the connection string so no variable issues
  • using the --unstable flag & the --allow-all
  • ensure all packages are up-to-date
  • ensure that my IP address is white-listed in mongo db
    • "(includes your current IP address)" is listed next to my whitelist on Atlas
  • Copying the exact same deno app to my Ubuntu on Windows (WSL2) and running it there - works in Ubuntu

What I've tried outside of DENO (no work around found)

  • Installed Mongosh CLI onto my PC
    • Connected to the atlas server using the mongodb+srv:// record OK
    • This proves that my IP is white listed
  • Setup a mongo db image on Docker Desktop using image mongodb/mongodb-community-server:latest
    • Without changing other code in my app, changed only the URI to connect to mongodb://127.0.0.1:27017 works OK
  • Using node + mongoose. Tested the mongoose driver (v8.4.4) and the same user/pass + the atlas mongodb+srv:// record - works OK

Versions

deno 1.44.4 (release, x86_64-pc-windows-msvc) ...Ubuntu Version: deno 1.44.4 (release, x86_64-unknown-linux-gnu) v8 12.6.228.9 typescript 5.4.5 "mongoose": "npm:[email protected]" Windows 11 v23H2 (OS Build 22631.3737)


Related issues

This seems to be related to an issue on the mongoose GitHub page, but was closed as 'underlying library issue' with a recommendation to upgrade to mongoose v8, however that doesn't seem to have helped. https://github.com/Automattic/mongoose/issues/13988

Original issue seems to only happen on Windows, only on Deno, only with Atlas, only on certain WiFi, and only on Mongoose 7. I'm able to repro with Mongoose 7.6.3 on @IslandRhythms 's machine, but the issue comes down to the fact that tls.connect() hangs here. The socket never emits any events. There isn't much more we can do to fix this particular error, other than recommend upgrading to Mongoose 8, which seems to be unaffected.


The error from the console when running from VS Code

connectionString mongodb+srv://<REMOVED_USER>:<REMOVED_PASS>@cluster0.<REMOVED>.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0
error: Uncaught (in promise) MongooseServerSelectionError: connection timed out
    at _handleConnectionErrors (file:///C:/Users/jayan/AppData/Local/deno/npm/registry.npmjs.org/mongoose/8.4.3/lib/connection.js:897:11)
    at NativeConnection.openUri (file:///C:/Users/jayan/AppData/Local/deno/npm/registry.npmjs.org/mongoose/8.4.3/lib/connection.js:848:11)
    at eventLoopTick (ext:core/01_core.js:207:9)
    at async DB.connect (file:///D:/DevWork/<REMOVED_MY_APP_NAME>/config/db.ts:62:5)
    at async file:///D:/DevWork/<REMOVED_MY_APP_NAME>/config/db.ts:79:1
Watcher Process failed. Restarting on file change...

Error when running VSCode debugger in Edge

(To be honest, I've never done any debugging like this and thought if I tried I might be able to find something. I was wrong - I have no idea, so ignore if this doesn't help)

MongoNetworkTimeoutError: connection timed out
    at connectionFailureError (file:///C:/Users/jayan/AppData/Local/deno/npm/registry.npmjs.org/mongodb/6.6.2/lib/cmap/connect.js:355:20)
    at TLSSocket.<anonymous> (file:///C:/Users/jayan/AppData/Local/deno/npm/registry.npmjs.org/mongodb/6.6.2/lib/cmap/connect.js:269:43)
    at Object.onceWrapper (ext:deno_node/_stream.mjs:1926:32)
    at TLSSocket.emit (ext:deno_node/_stream.mjs:1851:9)
    at TLSSocket._onTimeout (node:net:849:10)
    at cb (ext:deno_node/internal/timers.mjs:64:31)
    at eventLoopTick (ext:core/01_core.js:203:13)

jantoney avatar Jun 29 '24 05:06 jantoney

@littledivy - Hey, saw you got tagged in this a while ago and wondering if you're the person to assist, or tag the right person? I have no idea where this error lies given it's only deno and only windows.

I've now upgraded all the modules and deno - Still the same timeout issue.

I can see hazelnutcloud found an issue (https://github.com/denoland/deno/issues/16633#issuecomment-1482619798) where deno was adding an extra . to the end of the domain names and this was fixed in https://github.com/mongodb/node-mongodb-native/commit/051b8615ac0ebebb8c07d7a661bf1ab4f99cf4b2 I can confirm Deno is still adding these, but it shouldn't (?) be an issue now...?

Any help appreciated please.

Versioning

deno 2.0.0 (stable, release, x86_64-pc-windows-msvc)
v8 12.9.202.13-rusty
typescript 5.6.2
---
"npm:mongodb@^6.9.0": "6.9.0",
"npm:mongoose@^8.7.1": "8.7.1"

Node test code for the DNS

I've replaced things between {...}

const dns = require('node:dns');

dns.promises.resolveSrv("_mongodb._tcp.cluster0.{CLUSTER}.mongodb.net")
    .then(console.log)
    .catch(console.error);
[
  {
    name: 'ac-nrwnbvi-shard-00-02.{CLUSTER}.mongodb.net',
    port: 27017,
    priority: 0,
    weight: 0
  },
  {
    name: 'ac-nrwnbvi-shard-00-00.{CLUSTER}.mongodb.net',
    port: 27017,
    priority: 0,
    weight: 0
  },
  {
    name: 'ac-nrwnbvi-shard-00-01.{CLUSTER}.mongodb.net',
    port: 27017,
    priority: 0,
    weight: 0
  }
]

Deno test code for the DNS

I've replaced things between {...}

import dns from "node:dns";
console.log('start')

console.log(dns.resolveSrv("_mongodb._tcp.cluster0.{CLUSTER}.mongodb.net", (err, res) => {
    console.log(res)
}))
[
  {
    priority: 0,
    weight: 0,
    port: 27017,
    name: "ac-nrwnbvi-shard-00-01.{CLUSTER}.mongodb.net."
  },
  {
    priority: 0,
    weight: 0,
    port: 27017,
    name: "ac-nrwnbvi-shard-00-00.{CLUSTER}.mongodb.net."
  },
  {
    priority: 0,
    weight: 0,
    port: 27017,
    name: "ac-nrwnbvi-shard-00-02.{CLUSTER}.mongodb.net."
  }
]

Example Code

The most basic code example possible. I've replaced things between {...}


const uri = "mongodb+srv://{USER_ID}:{PASSWORD}@cluster0.{CLUSTER}.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0";

import mongoose from 'mongoose';
console.log('Connecting to MongoDB...');
mongoose.connect(uri)
  .then(() => {
    console.log('Connected to MongoDB');

  })
  .catch((err) => {
    console.error('Error connecting to MongoDB', err);
  });

Full Error

I've replaced things between {...}

Connecting to MongoDB...
Error connecting to MongoDB MongooseServerSelectionError: connection timed out
    at _handleConnectionErrors (file:///C:/Users/jayan/AppData/Local/deno/npm/registry.npmjs.org/mongoose/8.7.1/lib/connection.js:909:11)
    at NativeConnection.openUri (file:///C:/Users/jayan/AppData/Local/deno/npm/registry.npmjs.org/mongoose/8.7.1/lib/connection.js:860:11)
    at eventLoopTick (ext:core/01_core.js:214:9) {
  message: "connection timed out",
  reason: TopologyDescription {
    type: "ReplicaSetNoPrimary",
    servers: Map(3) {
      "ac-nrwnbvi-shard-00-02.{CLUSTER}.mongodb.net.:27017" => ServerDescription {
        address: "ac-nrwnbvi-shard-00-02.{CLUSTER}.mongodb.net.:27017",
        type: "Unknown",
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        minRoundTripTime: 0,
        lastUpdateTime: 30886,
        lastWriteDate: 0,
        error: MongoNetworkTimeoutError: connection timed out
    at connectionFailureError (file:///C:/Users/jayan/AppData/Local/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/cmap/connect.js:358:20)
    at TLSSocket.<anonymous> (file:///C:/Users/jayan/AppData/Local/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/cmap/connect.js:273:43)
    at Object.onceWrapper (ext:deno_node/_events.mjs:516:28)
    at TLSSocket.emit (ext:deno_node/_events.mjs:393:28)
    at TLSSocket._onTimeout (node:net:849:10)
    at cb (ext:deno_node/internal/timers.mjs:64:31)
    at callback (ext:deno_web/02_timers.js:68:7)
    at eventLoopTick (ext:core/01_core.js:210:13) {
          [Symbol(errorLabels)]: [Set]
        },
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        "$clusterTime": null
      },
      "ac-nrwnbvi-shard-00-00.{CLUSTER}.mongodb.net.:27017" => ServerDescription {
        address: "ac-nrwnbvi-shard-00-00.{CLUSTER}.mongodb.net.:27017",
        type: "Unknown",
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        minRoundTripTime: 0,
        lastUpdateTime: 30889,
        lastWriteDate: 0,
        error: MongoNetworkTimeoutError: connection timed out
    at connectionFailureError (file:///C:/Users/jayan/AppData/Local/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/cmap/connect.js:358:20)
    at TLSSocket.<anonymous> (file:///C:/Users/jayan/AppData/Local/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/cmap/connect.js:273:43)
    at Object.onceWrapper (ext:deno_node/_events.mjs:516:28)
    at TLSSocket.emit (ext:deno_node/_events.mjs:393:28)
    at TLSSocket._onTimeout (node:net:849:10)
    at cb (ext:deno_node/internal/timers.mjs:64:31)
    at callback (ext:deno_web/02_timers.js:68:7)
    at eventLoopTick (ext:core/01_core.js:210:13) {
          [Symbol(errorLabels)]: [Set]
        },
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        "$clusterTime": null
      },
      "ac-nrwnbvi-shard-00-01.{CLUSTER}.mongodb.net.:27017" => ServerDescription {
        address: "ac-nrwnbvi-shard-00-01.{CLUSTER}.mongodb.net.:27017",
        type: "Unknown",
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        minRoundTripTime: 0,
        lastUpdateTime: 30900,
        lastWriteDate: 0,
        error: MongoNetworkTimeoutError: connection timed out
    at connectionFailureError (file:///C:/Users/jayan/AppData/Local/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/cmap/connect.js:358:20)
    at TLSSocket.<anonymous> (file:///C:/Users/jayan/AppData/Local/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/cmap/connect.js:273:43)
    at Object.onceWrapper (ext:deno_node/_events.mjs:516:28)
    at TLSSocket.emit (ext:deno_node/_events.mjs:393:28)
    at TLSSocket._onTimeout (node:net:849:10)
    at cb (ext:deno_node/internal/timers.mjs:64:31)
    at callback (ext:deno_web/02_timers.js:68:7)
    at eventLoopTick (ext:core/01_core.js:210:13) {
          [Symbol(errorLabels)]: [Set]
        },
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        setVersion: null,
        setVersion: null,
        setVersion: null,
        setVersion: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        setVersion: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        "$clusterTime": null
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: "atlas-fcj4xn-shard-0",
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}

jantoney avatar Oct 12 '24 08:10 jantoney

This might be related to https://github.com/denoland/deno/issues/26413 (which seems to be fixed on 2.0.4+770ef14 canary) Are you able to connect without Mongoose?

Zizaco avatar Nov 05 '24 20:11 Zizaco

Still an issue in deno 2.1.4 on windows 10 using mongoose 8.8.3

deno 2.1.4 (stable, release, x86_64-pc-windows-msvc)
v8 13.0.245.12-rusty
typescript 5.6.2

lgigrl avatar Dec 18 '24 17:12 lgigrl

Is the ip address set to 0.0.0.0 in mongoDB atlas?

nav2924 avatar Apr 19 '25 06:04 nav2924

Connecting to an atlas cluster with 0.0.0.0 ip access and restricted ip access seems to work fine with latest canary deno 2.4.4+80c0998.

const uri = "mongodb+srv://<user>:<pwd>@cluster0.<cluster>.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0";

import mongoose from 'mongoose';
console.log('Connecting to MongoDB...');
mongoose.connect(uri)
  .then(() => {
    console.log('Connected to MongoDB');

  })
  .catch((err) => {
    console.error('Error connecting to MongoDB', err);
  });
$ deno -A test.mjs
Connecting to MongoDB...
Connected to MongoDB

littledivy avatar Aug 17 '25 07:08 littledivy

Closing as it seems to work fine with Deno 2.4.4 and above.

littledivy avatar Aug 28 '25 12:08 littledivy