API and Microservices Test no 3 : cannot connect to mongodb

I’ve completed the API & Microservices lesson, including MongoDB & Mongoose sub-curriculum. I created my mongoDB account, connect to my cluster from glitch, and finish the practice successfully.

And then i came into the 3rd test which required required database connection.

I get the connection string from mongodb site : mongodb+srv://<username>:<password>@petrandorichard-ltdkc.mongodb.net/test?retryWrites=true&w=majority
put my cluster credentials (username & password) and connect
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });

only this time, it doesn’t work since testing it with mongoose.connection.readyState resulted in 0, which indicates failed connection.

Any suggestion please?

The warning shows in console is

(node:137) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/4.x/docs/connections.html#use-mongo-client

It means if you have mongoose version less than or equal to 4.11.0 and you are using connect() function so you need to set useMongoClient option i.e.

mongoose.connect(process.env.MONGO_URI, {useMongoClient: true, }); 

When You use the above code to connect it shows you an error i.e. Error: Invalid mongodb uri .to solve this error check your mongodb string .
For me it is working if I remove +srv from your string.

One thing always remember if you want to keep your mongodb string safe always put it into .env file on glitch.

1 Like

Thank you! :grinning: