简体   繁体   中英

How to authenticate to MongoDB with NodeJS and also PM2 to run Node constantly

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.

Uncomment bindIp and set it to 127.0.0.1

bindIp = 127.0.0.1

security:
     authentication: enabled

this will solve your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM