deno icon indicating copy to clipboard operation
deno copied to clipboard

`version 2.0.1` breaks npm:MongoDB compatibility

Open Zizaco opened this issue 1 year ago • 9 comments

Version: Deno 2.0.1 and 2.0.2 MongoDB Package Version npm:mongodb@^6.9.0

I was working on a project using MongoDB when I learned that there was a new version available (2.0.2). After upgrading, all my tests started failing, as the new version was unable to establish a database connection.

I was able to isolate and reproduce it directly from the repl:

$  atlas deployments list
NAME       TYPE    MDB VER   STATE
cluster0   LOCAL   8.0.1     IDLE

To list both local and cloud Atlas deployments, authenticate to your Atlas account using the "atlas login" command.
$  deno upgrade 2.0.2
Current Deno version: v2.0.0
Downloading https://github.com/denoland/deno/releases/download/v2.0.2/deno-x86_64-unknown-linux-gnu.zip
Deno is upgrading to version 2.0.2

Upgraded successfully to Deno v2.0.2 (stable)

$  deno --version
deno 2.0.2 (stable, release, x86_64-unknown-linux-gnu)
v8 12.9.202.13-rusty
typescript 5.6.2
$  cat deno.json | grep npm:mongo
    "mongodb": "npm:mongodb@^6.9.0"
$  deno
Deno 2.0.2
exit using ctrl+d, ctrl+c, or close()
REPL is running with all permissions allowed.
To specify permissions, run `deno repl` with allow flags.
> import { MongoClient } from "mongodb";
undefined
> const mongoClient = new MongoClient("mongodb://127.0.0.1:27017");
undefined
> await mongoClient.connect() // it takes a few seconds to throw
Uncaught MongoServerSelectionError: connect ECONNREFUSED ::1:27017 - Local (undefined:undefined)
    at Topology.selectServer (file:///home/zizaco/.cache/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/sdam/topology.js:303:38)
    at eventLoopTick (ext:core/01_core.js:214:9)
    at async Topology._connect (file:///home/zizaco/.cache/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/sdam/topology.js:196:28)
    at async Topology.connect (file:///home/zizaco/.cache/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/sdam/topology.js:158:13)
    at async topologyConnect (file:///home/zizaco/.cache/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/mongo_client.js:209:17)
    at async MongoClient._connect (file:///home/zizaco/.cache/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/mongo_client.js:222:13)
    at async MongoClient.connect (file:///home/zizaco/.cache/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/mongo_client.js:147:13)
    at async <anonymous>:1:22
>

BTW, it works perfectly with Deno 2.0.0

$  atlas deployments list
NAME       TYPE    MDB VER   STATE
cluster0   LOCAL   8.0.1     IDLE

To list both local and cloud Atlas deployments, authenticate to your Atlas account using the "atlas login" command.
$  deno upgrade 2.0.0
Current Deno version: v2.0.2
Downloading https://github.com/denoland/deno/releases/download/v2.0.0/deno-x86_64-unknown-linux-gnu.zip
Deno is upgrading to version 2.0.0

Upgraded successfully to Deno v2.0.0 (stable)

$  deno --version
deno 2.0.0 (stable, release, x86_64-unknown-linux-gnu)
v8 12.9.202.13-rusty
typescript 5.6.2
$  cat deno.json | grep npm:mongo
    "mongodb": "npm:mongodb@^6.9.0"
$  deno
Deno 2.0.0
exit using ctrl+d, ctrl+c, or close()
REPL is running with all permissions allowed.
To specify permissions, run `deno repl` with allow flags.
> import { MongoClient } from "mongodb";
undefined
> const mongoClient = new MongoClient("mongodb://127.0.0.1:27017");
undefined
> await mongoClient.connect() // resolves very quickly
<ref *1> MongoClient {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  mongoLogger: undefined,
  s: {
    url: "mongodb://127.0.0.1:27017",
  }
  # [...]
} 
>
# success. All other db operations work (transactions, change streams, crud)

Zizaco avatar Oct 19 '24 16:10 Zizaco

The same issue occurs with Deno 2.0.1. Only v2.0.0 works.

$  deno upgrade 2.0.1
Current Deno version: v2.0.0
Downloading https://github.com/denoland/deno/releases/download/v2.0.1/deno-x86_64-unknown-linux-gnu.zip
Deno is upgrading to version 2.0.1

Upgraded successfully to Deno v2.0.1 (stable)

$  deno
Deno 2.0.1
exit using ctrl+d, ctrl+c, or close()
REPL is running with all permissions allowed.
To specify permissions, run `deno repl` with allow flags.
> import { MongoClient } from "mongodb";
undefined
> const mongoClient = new MongoClient("mongodb://127.0.0.1:27017");
undefined
> await mongoClient.connect() // it takes a few seconds to throw
Uncaught MongoServerSelectionError: Cannot read properties of undefined (reading 'setNoDelay')
    at Topology.selectServer (file:///home/zizaco/.cache/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/sdam/topology.js:303:38)
    at eventLoopTick (ext:core/01_core.js:214:9)
    at async Topology._connect (file:///home/zizaco/.cache/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/sdam/topology.js:196:28)
    at async Topology.connect (file:///home/zizaco/.cache/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/sdam/topology.js:158:13)
    at async topologyConnect (file:///home/zizaco/.cache/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/mongo_client.js:209:17)
    at async MongoClient._connect (file:///home/zizaco/.cache/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/mongo_client.js:222:13)
    at async MongoClient.connect (file:///home/zizaco/.cache/deno/npm/registry.npmjs.org/mongodb/6.9.0/lib/mongo_client.js:147:13)
    at async <anonymous>:1:22
>

Zizaco avatar Oct 19 '24 17:10 Zizaco

@Zizaco FYI: The Cannot read properties of undefined (reading 'setNoDelay') is fixed in 2.0.2. It was a regression and the reason we pulled 2.0.1

marvinhagemeister avatar Oct 19 '24 17:10 marvinhagemeister

Just tried with deno 2.0.2 and it seems to work:

import { MongoClient } from "npm:mongodb";

const mongoClient = new MongoClient("mongodb://127.0.0.1:27017");
console.log(await mongoClient.connect())
<ref *1> MongoClient {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  mongoLogger: undefined,
  s: {
    url: "mongodb://127.0.0.1:27017",
    bsonOptions: {
      raw: false,
      useBigInt64: false,
      promoteLongs: true,
      promoteValues: true,
      promoteBuffers: false,
      ignoreUndefined: false,
      bsonRegExp: false,
      serializeFunctions: false,
      fieldsAsRaw: {},
      enableUtf8Validation: true
    },
    namespace: MongoDBNamespace { db: "admin", collection: undefined },
    hasBeenClosed: false,
    sessionPool: ServerSessionPool {
      client: [Circular *1],
      sessions: List {
        count: 0,
        head: <ref *2> {
          next: [Circular *2],
          prev: [Circular *2],
          value: null
        }
      }
    },
    activeSessions: Set(0) {},
    authProviders: MongoClientAuthProviders { existingProviders: Map(0) {} },
    options: [Getter],
    readConcern: [Getter],
    writeConcern: [Getter],
    readPreference: [Getter],
    isMongoClient: [Getter]
  },
  topology: <ref *3> Topology {
    _events: [Object: null prototype] {
      connectionPoolCreated: [Function (anonymous)],
      connectionPoolReady: [Function (anonymous)],
      connectionPoolCleared: [Function (anonymous)],
      connectionPoolClosed: [Function (anonymous)],
      connectionCreated: [Function (anonymous)],
      connectionReady: [Function (anonymous)],
      connectionClosed: [Function (anonymous)],
      connectionCheckOutStarted: [Function (anonymous)],
      connectionCheckOutFailed: [Function (anonymous)],
      connectionCheckedOut: [Function (anonymous)],
      connectionCheckedIn: [Function (anonymous)],
      commandStarted: [Function (anonymous)],
      commandSucceeded: [Function (anonymous)],
      commandFailed: [Function (anonymous)],
      serverOpening: [Function (anonymous)],
      serverClosed: [Function (anonymous)],
      serverDescriptionChanged: [Function (anonymous)],
      topologyOpening: [Function (anonymous)],
      topologyClosed: [Function (anonymous)],
      topologyDescriptionChanged: [Function (anonymous)],
      error: [Function (anonymous)],
      timeout: [Function (anonymous)],
      close: [Function (anonymous)],
      serverHeartbeatStarted: [Function (anonymous)],
      serverHeartbeatSucceeded: [Function (anonymous)],
      serverHeartbeatFailed: [Function (anonymous)]
    },
    _eventsCount: 26,
    _maxListeners: undefined,
    client: [Circular *1],
    s: {
      id: 0,
      options: [Object: null prototype] {
        hosts: [ new HostAddress('127.0.0.1:27017') ],
        compressors: [ "none" ],
        connectTimeoutMS: 30000,
        directConnection: false,
        driverInfo: {},
        enableUtf8Validation: true,
        forceServerObjectId: false,
        heartbeatFrequencyMS: 10000,
        loadBalanced: false,
        localThresholdMS: 15,
        maxConnecting: 2,
        maxIdleTimeMS: 0,
        maxPoolSize: 100,
        minPoolSize: 0,
        minHeartbeatFrequencyMS: 500,
        monitorCommands: false,
        noDelay: true,
        pkFactory: { createPk: [Function: createPk] },
        raw: false,
        readPreference: ReadPreference {
          mode: "primary",
          tags: undefined,
          hedge: undefined,
          maxStalenessSeconds: undefined,
          minWireVersion: undefined
        },
        retryReads: true,
        retryWrites: true,
        serverMonitoringMode: "auto",
        serverSelectionTimeoutMS: 30000,
        socketTimeoutMS: 0,
        srvMaxHosts: 0,
        srvServiceName: "mongodb",
        waitQueueTimeoutMS: 0,
        zlibCompressionLevel: 0,
        dbName: "test",
        userSpecifiedAuthSource: false,
        userSpecifiedReplicaSet: false,
        mongoLoggerOptions: {
          componentSeverities: [Object],
          maxDocumentLength: 1000,
          logDestination: [Object],
          logDestinationIsStdErr: true
        },
        metadata: { driver: [Object], platform: "Deno v2.0.2, LE", os: [Object] },
        extendedMetadata: Promise { [Object] },
        [Symbol("@@mdb.enableMongoLogger")]: false
      },
      seedlist: [ new HostAddress('127.0.0.1:27017') ],
      state: "connected",
      description: TopologyDescription {
        type: "Single",
        servers: Map(1) { "127.0.0.1:27017" => [ServerDescription] },
        stale: false,
        compatible: true,
        heartbeatFrequencyMS: 10000,
        localThresholdMS: 15,
        setName: null,
        maxElectionId: null,
        maxSetVersion: null,
        commonWireVersion: 0,
        logicalSessionTimeoutMinutes: 30
      },
      serverSelectionTimeoutMS: 30000,
      heartbeatFrequencyMS: 10000,
      minHeartbeatFrequencyMS: 500,
      servers: Map(1) {
        "127.0.0.1:27017" => Server {
          _events: [Object: null prototype],
          _eventsCount: 18,
          _maxListeners: undefined,
          serverApi: undefined,
          topology: [Circular *3],
          pool: [ConnectionPool],
          s: [Object],
          monitor: [Monitor],
          [Symbol(kCapture)]: false
        }
      },
      credentials: undefined,
      clusterTime: undefined,
      connectionTimers: Set(0) {},
      detectShardedTopology: [Function: detectShardedTopology],
      detectSrvRecords: [Function: detectSrvRecords]
    },
    mongoLogger: undefined,
    component: "topology",
    connectionLock: undefined,
    [Symbol(kCapture)]: false,
    [Symbol(waitQueue)]: List {
      count: 0,
      head: <ref *4> {
        next: [Circular *4],
        prev: [Circular *4],
        value: null
      }
    }
  },
  connectionLock: undefined,
  [Symbol(kCapture)]: false,
  [Symbol(options)]: [Object: null prototype] {
    hosts: [ new HostAddress('127.0.0.1:27017') ],
    compressors: [ "none" ],
    connectTimeoutMS: 30000,
    directConnection: false,
    driverInfo: {},
    enableUtf8Validation: true,
    forceServerObjectId: false,
    heartbeatFrequencyMS: 10000,
    loadBalanced: false,
    localThresholdMS: 15,
    maxConnecting: 2,
    maxIdleTimeMS: 0,
    maxPoolSize: 100,
    minPoolSize: 0,
    minHeartbeatFrequencyMS: 500,
    monitorCommands: false,
    noDelay: true,
    pkFactory: { createPk: [Function: createPk] },
    raw: false,
    readPreference: ReadPreference {
      mode: "primary",
      tags: undefined,
      hedge: undefined,
      maxStalenessSeconds: undefined,
      minWireVersion: undefined
    },
    retryReads: true,
    retryWrites: true,
    serverMonitoringMode: "auto",
    serverSelectionTimeoutMS: 30000,
    socketTimeoutMS: 0,
    srvMaxHosts: 0,
    srvServiceName: "mongodb",
    waitQueueTimeoutMS: 0,
    zlibCompressionLevel: 0,
    dbName: "test",
    userSpecifiedAuthSource: false,
    userSpecifiedReplicaSet: false,
    mongoLoggerOptions: {
      componentSeverities: {
        command: "off",
        topology: "off",
        serverSelection: "off",
        connection: "off",
        client: "off",
        default: "off"
      },
      maxDocumentLength: 1000,
      logDestination: { write: [Function (anonymous)] },
      logDestinationIsStdErr: true
    },
    metadata: {
      driver: { name: "nodejs", version: "6.8.0" },
      platform: "Deno v2.0.2, LE",
      os: {
        name: "darwin",
        architecture: "arm64",
        version: "24.0.0",
        type: "Darwin"
      }
    },
    extendedMetadata: Promise {
      {
        driver: { name: "nodejs", version: "6.8.0" },
        platform: "Deno v2.0.2, LE",
        os: {
          name: "darwin",
          architecture: "arm64",
          version: "24.0.0",
          type: "Darwin"
        }
      }
    },
    [Symbol("@@mdb.enableMongoLogger")]: false
  }
}

littledivy avatar Oct 25 '24 02:10 littledivy

Just tried with deno 2.0.2 and it seems to work:

Here's a step-by-step on how to reproduce it:

deno_mongodb_issue

Other details:

OS: Ubuntu 20.04.6 LTS
Kernel: 5.15.0-124-generic
CPU: Intel i7-10510U (8) @ 4.900GHz
Local MongoDB 8.0.1 - single node replica-set

MongoDB Details

$  mongosh
Current Mongosh Log ID: 671b33795bd864d314fe6910
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.3.2
Using MongoDB:          8.0.1
Using Mongosh:          2.3.2

For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/

Warning: Found ~/.mongorc.js, but not ~/.mongoshrc.js. ~/.mongorc.js will not be loaded.
  You may want to copy or rename ~/.mongorc.js to ~/.mongoshrc.js.
AtlasLocalDev rs-localdev [direct: primary] test> rs.status()
{
  set: 'rs-localdev',
  date: ISODate('2024-10-25T05:58:24.738Z'),
  myState: 1,
  term: Long('4'),
  syncSourceHost: '',
  syncSourceId: -1,
  heartbeatIntervalMillis: Long('2000'),
  majorityVoteCount: 1,
  writeMajorityCount: 1,
  votingMembersCount: 1,
  writableVotingMembersCount: 1,
  optimes: {
    lastCommittedOpTime: { ts: Timestamp({ t: 1729835904, i: 1 }), t: Long('4') },
    lastCommittedWallTime: ISODate('2024-10-25T05:58:24.193Z'),
    readConcernMajorityOpTime: { ts: Timestamp({ t: 1729835904, i: 1 }), t: Long('4') },
    appliedOpTime: { ts: Timestamp({ t: 1729835904, i: 1 }), t: Long('4') },
    durableOpTime: { ts: Timestamp({ t: 1729835904, i: 1 }), t: Long('4') },
    writtenOpTime: { ts: Timestamp({ t: 1729835904, i: 1 }), t: Long('4') },
    lastAppliedWallTime: ISODate('2024-10-25T05:58:24.193Z'),
    lastDurableWallTime: ISODate('2024-10-25T05:58:24.193Z'),
    lastWrittenWallTime: ISODate('2024-10-25T05:58:24.193Z')
  },
  lastStableRecoveryTimestamp: Timestamp({ t: 1729835864, i: 1 }),
  electionCandidateMetrics: {
    lastElectionReason: 'electionTimeout',
    lastElectionDate: ISODate('2024-10-25T05:33:44.075Z'),
    electionTerm: Long('4'),
    lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 0, i: 0 }), t: Long('-1') },
    lastSeenWrittenOpTimeAtElection: { ts: Timestamp({ t: 1729463723, i: 1 }), t: Long('3') },
    lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1729463723, i: 1 }), t: Long('3') },
    numVotesNeeded: 1,
    priorityAtElection: 1,
    electionTimeoutMillis: Long('10000'),
    newTermStartDate: ISODate('2024-10-25T05:33:44.128Z'),
    wMajorityWriteAvailabilityDate: ISODate('2024-10-25T05:33:44.242Z')
  },
  members: [
    {
      _id: 0,
      name: 'localhost:27017',
      health: 1,
      state: 1,
      stateStr: 'PRIMARY',
      uptime: 1482,
      optime: { ts: Timestamp({ t: 1729835904, i: 1 }), t: Long('4') },
      optimeDate: ISODate('2024-10-25T05:58:24.000Z'),
      optimeWritten: { ts: Timestamp({ t: 1729835904, i: 1 }), t: Long('4') },
      optimeWrittenDate: ISODate('2024-10-25T05:58:24.000Z'),
      lastAppliedWallTime: ISODate('2024-10-25T05:58:24.193Z'),
      lastDurableWallTime: ISODate('2024-10-25T05:58:24.193Z'),
      lastWrittenWallTime: ISODate('2024-10-25T05:58:24.193Z'),
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      electionTime: Timestamp({ t: 1729834424, i: 1 }),
      electionDate: ISODate('2024-10-25T05:33:44.000Z'),
      configVersion: 1,
      configTerm: 4,
      self: true,
      lastHeartbeatMessage: ''
    }
  ],
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp({ t: 1729835904, i: 1 }),
    signature: {
      hash: Binary.createFromBase64('AAAAAAAAAAAAAAAAAAAAAAAAAAA=', 0),
      keyId: Long('0')
    }
  },
  operationTime: Timestamp({ t: 1729835904, i: 1 })
}

Zizaco avatar Oct 25 '24 06:10 Zizaco

@littledivy I reproduced the same issue on another computer (mac):

deno_mongodb_issue_macos_slow

Other details:

OS: macOS 14.6.1 (23G93)
Kernel: Darwin M-YM6352MQ40 23.6.0
CPU: Apple M1 Pro
Local MongoDB 8.0.1 - single node replica-set (docker via atlas cli)

MongoDB Details

 mongosh
Current Mongosh Log ID: 671b39c6b196fa0f36fb10ab
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.3.2
Using MongoDB:          8.0.1
Using Mongosh:          2.3.2

For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/

AtlasLocalDev cluster-local [direct: primary] test> rs.status()
{
  set: 'cluster-local',
  date: ISODate('2024-10-25T06:25:20.963Z'),
  myState: 1,
  term: Long('3'),
  syncSourceHost: '',
  syncSourceId: -1,
  heartbeatIntervalMillis: Long('2000'),
  majorityVoteCount: 1,
  writeMajorityCount: 1,
  votingMembersCount: 1,
  writableVotingMembersCount: 1,
  optimes: {
    lastCommittedOpTime: { ts: Timestamp({ t: 1729837511, i: 1 }), t: Long('3') },
    lastCommittedWallTime: ISODate('2024-10-25T06:25:11.690Z'),
    readConcernMajorityOpTime: { ts: Timestamp({ t: 1729837511, i: 1 }), t: Long('3') },
    appliedOpTime: { ts: Timestamp({ t: 1729837511, i: 1 }), t: Long('3') },
    durableOpTime: { ts: Timestamp({ t: 1729837511, i: 1 }), t: Long('3') },
    writtenOpTime: { ts: Timestamp({ t: 1729837511, i: 1 }), t: Long('3') },
    lastAppliedWallTime: ISODate('2024-10-25T06:25:11.690Z'),
    lastDurableWallTime: ISODate('2024-10-25T06:25:11.690Z'),
    lastWrittenWallTime: ISODate('2024-10-25T06:25:11.690Z')
  },
  lastStableRecoveryTimestamp: Timestamp({ t: 1729837501, i: 1 }),
  electionCandidateMetrics: {
    lastElectionReason: 'electionTimeout',
    lastElectionDate: ISODate('2024-10-25T06:03:11.249Z'),
    electionTerm: Long('3'),
    lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 0, i: 0 }), t: Long('-1') },
    lastSeenWrittenOpTimeAtElection: { ts: Timestamp({ t: 1729666832, i: 1 }), t: Long('2') },
    lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1729666832, i: 1 }), t: Long('2') },
    numVotesNeeded: 1,
    priorityAtElection: 1,
    electionTimeoutMillis: Long('10000'),
    newTermStartDate: ISODate('2024-10-25T06:03:11.251Z'),
    wMajorityWriteAvailabilityDate: ISODate('2024-10-25T06:03:11.352Z')
  },
  members: [
    {
      _id: 0,
      name: 'cluster-local:27017',
      health: 1,
      state: 1,
      stateStr: 'PRIMARY',
      uptime: 1336,
      optime: { ts: Timestamp({ t: 1729837511, i: 1 }), t: Long('3') },
      optimeDate: ISODate('2024-10-25T06:25:11.000Z'),
      optimeWritten: { ts: Timestamp({ t: 1729837511, i: 1 }), t: Long('3') },
      optimeWrittenDate: ISODate('2024-10-25T06:25:11.000Z'),
      lastAppliedWallTime: ISODate('2024-10-25T06:25:11.690Z'),
      lastDurableWallTime: ISODate('2024-10-25T06:25:11.690Z'),
      lastWrittenWallTime: ISODate('2024-10-25T06:25:11.690Z'),
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      electionTime: Timestamp({ t: 1729836191, i: 1 }),
      electionDate: ISODate('2024-10-25T06:03:11.000Z'),
      configVersion: 1,
      configTerm: 3,
      self: true,
      lastHeartbeatMessage: ''
    }
  ],
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp({ t: 1729837511, i: 1 }),
    signature: {
      hash: Binary.createFromBase64('AAAAAAAAAAAAAAAAAAAAAAAAAAA=', 0),
      keyId: Long('0')
    }
  },
  operationTime: Timestamp({ t: 1729837511, i: 1 })
}

Zizaco avatar Oct 25 '24 06:10 Zizaco

@littledivy, could we re-open the issue?

Zizaco avatar Oct 25 '24 06:10 Zizaco

I did some testing and found it works with a standalone mongodb node but fails when using a one-node replica set. Here’s a step-by-step guide to reproduce the issue:

Steps to reproduce

Run a MongoDB replica set container using the Atlas CLI. A replica set, unlike a standalone node, supports ACID transactions and closely resembles production environments.

# make sure docker & atlas-cli are installed
brew install mongodb-atlas # see https://www.mongodb.com/docs/atlas/cli/current/atlas-cli-deploy-local/

# syntax sugar for docker run
# this will output the connection string (port), for instance "mongodb://localhost:32768/?directConnection=true"
atlas deployments setup local-rs --type local --force --mdbVersion 7.0

# syntax sugar for docker ps
atlas deployments ls

Copy and paste connection string into main_rs.js. For instance:

// main_rs.js
import { MongoClient } from "mongodb";

const mongoClient = new MongoClient("mongodb://localhost:32768/?directConnection=true");
console.log(await mongoClient.connect())

Attempt to connect with deno and node:

deno upgrade 2.0.2
deno run -A main_rs.js # ❌ fails
deno upgrade 2.0.0
deno run -A main_rs.js # ✅ works
node --version # v20.16.0
node main_rs.js # ✅ works

Remarks

Running MongoDB as a standalone node works on Deno 2.0.2; however, unlike a replica set, this is not recommended for production environments.

# example running mongodb as a standalone node. this seems to work in v2.0.2
docker run --name mongodb -d -p 27017:27017 -v $(pwd)/data:/data/db mongodb/mongodb-community-server:7.0-ubi9

thanks for taking the time to review this issue!

Zizaco avatar Oct 25 '24 20:10 Zizaco

Ah thanks, I didn't try it with replica set, now I can reproduce it.

littledivy avatar Oct 27 '24 03:10 littledivy

@Zizaco Can you try with latest canary? deno upgrade --canary

littledivy avatar Nov 05 '24 05:11 littledivy

@littledivy It works! I ran the same tests, and everything works on ver 2.0.4+770ef14. Thanks!

$  deno upgrade --canary
Current Deno version: v2.0.2
Looking up canary version

Found latest canary version 770ef1460085e1a1b706cc7f066e7b3ea5010eb0

Downloading https://dl.deno.land/canary/770ef1460085e1a1b706cc7f066e7b3ea5010eb0/deno-x86_64-unknown-linux-gnu.zip
Deno is upgrading to version 770ef1460085e1a1b706cc7f066e7b3ea5010eb0

Upgraded successfully to Deno 770ef1460085e1a1b706cc7f066e7b3ea5010eb0 (canary)

$  deno --version
deno 2.0.4+770ef14 (canary, release, x86_64-unknown-linux-gnu)
v8 12.9.202.13-rusty
typescript 5.6.2
$  deno run -A main.js 
<ref *1> MongoClient {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  mongoLogger: undefined,
  s: {
    url: "mongodb://127.0.0.1:27017",
    # [...]
  }
}
# success.

Other details:

OS: Ubuntu 20.04.6 LTS
Kernel: 5.15.0-124-generic
CPU: Intel i7-10510U (8) @ 4.900GHz
Local MongoDB 8.0.1 - single node replica-set

Zizaco avatar Nov 05 '24 20:11 Zizaco

Still doesnt work in windows Not sure about linux. Local it is fine but SRV based connection works from my IP and doenst work from any other IP. On Atlas access is set to 0.0.0.0

MongoDB connection failed: MongooseServerSelectionError: Server selection timed out after 5000 ms at _handleConnectionErrors (c:\home\git\anvil-api\node_modules\mongoose\lib\connection.js:909:11) at NativeConnection.openUri (c:\home\git\anvil-api\node_modules\mongoose\lib\connection.js:860:11) at eventLoopTick (ext:core/01_core.js:214:9) at async connectDB (file:///C:/home/git/anvil-api/src/config/db.ts:76:5) at async startApp (file:///C:/home/git/anvil-api/main.ts:20:7) { message: "Server selection timed out after 5000 ms", reason: TopologyDescription { type: "ReplicaSetNoPrimary",

vikash-voolu avatar Nov 28 '24 16:11 vikash-voolu

@vikash-voolu Can you open a new issue for it? It is likely a different bug than this one.

littledivy avatar Nov 28 '24 17:11 littledivy