Adil Ijaz
Adil Ijaz

Reputation: 352

MongoDB Atlas with NodeJS using Mongoose is not connecting

Hy, I start learning a nodejs with restapi. But I'm trying to connect my mongodb atlas but it is giving me that error:

MongoParseError: Invalid connection string
    at parseConnectionString (D:\Working\nodeJS\node_modules\mongodb\lib\core\uri_parser.js:573:21)
    at connect (D:\Working\nodeJS\node_modules\mongodb\lib\operations\connect.js:281:3)
    at D:\Working\nodeJS\node_modules\mongodb\lib\mongo_client.js:259:5
    at maybePromise (D:\Working\nodeJS\node_modules\mongodb\lib\utils.js:692:3)
    at MongoClient.connect (D:\Working\nodeJS\node_modules\mongodb\lib\mongo_client.js:255:10)
    at D:\Working\nodeJS\node_modules\mongoose\lib\connection.js:835:12
    at new Promise (<anonymous>)
    at NativeConnection.Connection.openUri (D:\Working\nodeJS\node_modules\mongoose\lib\connection.js:832:19)
    at D:\Working\nodeJS\node_modules\mongoose\lib\index.js:351:10
    at D:\Working\nodeJS\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
    at new Promise (<anonymous>)
    at promiseOrCallback (D:\Working\nodeJS\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
    at Mongoose._promiseOrCallback (D:\Working\nodeJS\node_modules\mongoose\lib\index.js:1149:10)
    at Mongoose.connect (D:\Working\nodeJS\node_modules\mongoose\lib\index.js:350:20)
    at Object.<anonymous> (D:\Working\nodeJS\mongo.js:5:10)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)

monogo.js

const mongoose = require('mongoose')
require('dotenv').config()
mongoose.Promise = global.Promise

mongoose.connect('process.env.MONGOURUI',{ 
    useUnifiedTopology: true,
    useNewUrlParser: true,
    useCreateIndex:true,
    useFindAndModify:false,
 })
 .then(() => console.log('MongoDB Connected...'))
    .catch((err) => console.log(err))

**MONGOURUI=mongodb+srv://nodejspassword:[email protected]/nodeApi?retryWrites=true&w=majority; **

Upvotes: 0

Views: 1017

Answers (2)

JIGNESH PATEL
JIGNESH PATEL

Reputation: 397

const mongoose = require('mongoose')
require('dotenv').config()
mongoose.Promise = global.Promise

mongoose.connect(process.env.MONGOURI,{ 
    useUnifiedTopology: true,
    useNewUrlParser: true,
    useCreateIndex:true,
    useFindAndModify:false,
 })
 .then(() => console.log('MongoDB Connected...'))
    .catch((err) => console.log(err))

You just need to remove single quotes from process.env.MONGOURI and it will work! and make sure that the MONGOURI variable name is the same in the .env file.

Upvotes: 2

Aditya Joshi
Aditya Joshi

Reputation: 1053

In order to connect to the atlas, make sure you have whitelisted your IP address. you can find the deleted steps here

Upvotes: 0

Related Questions