Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connection of deno to mongodb fails

Tags:

mongodb

deno

I'm trying to connect my deno application to mongodb but I get error.

import {MongoClient} from "https://deno.land/x/[email protected]/mod.ts";

const client = await new MongoClient();
await client.connect("mongodb+srv://deno:[email protected]/deno?retryWrites=true&w=majority");

const db = client.database("notes");

export default db;

everything seem to be fine but when I run the app, I get this error.

error: Uncaught (in promise) Error: MongoError: "Connection failed: failed to lookup address information: nodename nor servname provided, or not known"
                throw new MongoError(`Connection failed: ${e.message || e}`);
              ^
    at MongoClient.connect (client.ts:93:15)
    at async mongodb.ts:4:1
like image 447
SinaMN75 Avatar asked Oct 15 '22 22:10

SinaMN75


1 Answers

2 problems that I see:

  • The code snippet above only works with Mongo installed in local machine.
  • The connection string use DNS Seed List, but the current library couldn't resolve to a list of hosts

To make it works with Mongo Atlas, you need to call a connect method with difference parameters and find a correct (static) host instead a (dynamic) DNS Seed List:

const client = new MongoClient();

const db = await client.connect({
  db: '<your db or collection with work with>',
  tls: true,
  servers: [
    {
      host: '<correct host - the way to get the host - see bellow>',
      port: 27017,
    },
  ],
  credential: {
    username: '<your username>',
    password: '<your password>',
    mechanism: 'SCRAM-SHA-1',
  },
});

How to get the correct host:

  • Open your Cluster in Mongo Atlas
  • Select Connect button
  • Select Connect to application option
  • Select Driver: Node.js and Version: 2.2.12 or later
  • Here you will see a list of host follow @ character
like image 132
nthung.vlvn Avatar answered Oct 20 '22 16:10

nthung.vlvn