1

I am trying to authenticate my connect statement with mongoose to mongodb. I have

//In app.js

mongoose.connect('mongodb://localhost:27017/databasenamehere', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    user: 'username',
    pass: 'password'
});

with the /etc/mongo.conf file set up as

...
#bindIP //commented this out
...
security:
     authentication: enabled
...

And have also tried putting it into the .connect string as

//In app.js
mongoose.connect('mongodb://username:password@localhost:27017/databasenamehere', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

Also tried per the docs:

mongod --auth --port 27017 --dbpath /var/lib/mongodb

//and 

mongod --auth --port 27017 --dbpath /var/lib/mongodb

docs: https://docs.mongodb.com/manual/tutorial/enable-authentication/

but it is not working this way either. When I visit a page on my MEAN stack app that makes a call to NodeJS backend to get data from MongoDB in F12 (chrome developer tools) it shows that the call has a status of (failed) and says 'Failed to load response data'. The server I am using has Ubuntu 18.04.

I expect to see that the app.js will connect to mongoDB successfully with the user I have created in the mongoDB for the database I have selected that user to be for. Meaning I disabled the security (commented out above lines), created a user and gave readWrite privileges to the created user and tied to my desired DB, then turned security back on in the mongo.conf file as per the docs.

Also, would like to know how to use PM2 (npm install pm2) and have my backend nodeJS code always run so that Node will always be running my app.js so that API calls will be successful.

Retro
  • 113
  • 13

1 Answers1

0

Uncomment bindIp and set it to 127.0.0.1

bindIp = 127.0.0.1

security:
     authentication: enabled

this will solve your problem

Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
  • When I do that I get.. root@server:~# systemctl start mongod root@server:~# mongo MongoDB shell version v4.2.0 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb 2019-10-03T02:49:26.855+0000 E QUERY [js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused : connect@src/mongo/shell/mongo.js:341:17 @(connect):2:6 2019-10-03T02:49:26.861+0000 F-[main] exception: connect failed 2019-10-03T02:49:26.862+0000 E-[main] exiting with code 1 – Retro Oct 03 '19 at 02:50
  • https://stackoverflow.com/questions/13312358/mongo-couldnt-connect-to-server-127-0-0-127017 you can check this – Pushprajsinh Chudasama Oct 03 '19 at 05:11