'Unable to connect to Mongodb Atlas using mongoose

I am trying to connect to a cluster created in Mongodb Atlas using mongoose in node js and I am facing below issues when doing so.

  1. When I use the connection string that is given in the Mongo db atlasmongodb+srv://lm_dev_app:<password>@lmdev-q5biw.mongodb.net/test?retryWrites=true&w=majorityI get below error

    { Error: queryTxt EBADNAME lmdev-q5biw.mongodb.net at QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19) errno: 'EBADNAME', code: 'EBADNAME', syscall: 'queryTxt', hostname: 'lmdev-q5biw.mongodb.net'}

I cannot use this connection string in Mongodb Compass as well as I am getting the same error there.

  1. If I try to connect using mongodb://lm_dev_app:<password>@lmdev-shard-00-01-q5biw.mongodb.net/test i get below error

    MongooseServerSelectionError: connection to 54.66.221.230:27017 closed

However I am able to connect to each node using Mongodb Compass which eliminates the possibility of my ipaddress not being whitelisted.

Here is the sample code that I am using

const mongoosePromise = mongoose.connect("mongodb://lm_dev_app:<password>@lmdev-shard-00-01-q5biw.mongodb.net/test", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    replicaSet: "LMDEV"
}, (err) => {
    if (err) {
        console.log(err);
    } else {
        console.log("Successful");
    }
});

Any thoughts on what is happening here.



Solution 1:[1]

After trying different connection strings for several hours, I finally just copy/pasted the connection string from MongoDB Compass and it works! (first connect, then edit the connection string as it will change)

It looks like this:

mongodb+srv://username:[email protected]/test?authSource=admin&replicaSet=atlas-abcde-shard-0&readPreference=primary&appname=MongoDB%20Compass&ssl=true

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kristof