Website document installation tutorial: docs.mongodb.com/manual/tuto…

YUM configuration source

Repos. D /mongodb-org-5.0.repoCopy the code

Paste the following content into the file and save it

[mongo - org - 5.0] name = directing a Repository baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/5.0/x86_64/ gpgcheck = 1 enabled = 1 gpgkey=https://www.mongodb.org/static/pgp/server-5.0.ascCopy the code

Install the mongo

sudo yum install -y mongodb-org
Copy the code

Start the

Systemctl start mongod sudo systemctl start mongod Sudo systemctl restart mongodCopy the code

Viewing port Status

netstat -nptl | grep '27017'
Copy the code

Creating a User association

Background: AT this point I’m installing mongodb on a remote server, I don’t want everyone to be able to manipulate my database and want to be able to connect to my remote database via mongodb Compass.

Modifying a configuration file:

vim /etc/mongod.conf
Copy the code

Add to the document:

security:
  authorization: enabled
Copy the code

Restart the service

sudo systemctl restart mongod
Copy the code

Create a user

#Access to the mongo
mongo

#Using the Admin database
use admin 

#Create a user with root permission
db.createUser({ user: "root", pwd: "123123", roles: [{ role: "root", db: "admin" }] })

#exit
quit()

#Log in using the user password
mongo -u root -p --authenticationDatabase admin

#Add user rights (Add user rights to the root usertestIf you have the root permission, you can also read and write the database without the following permissions.
db.grantRolesToUser("root", [{role:"readWrite",db:"test"}])

Copy the code

After the user is added, the mongoose connection to the database in NodeJS should be written as follows:

/* Username: root password: 123123 database name: test AuthSource =admin is the required */
mongoose.connect('mongodb://root:123123@localhost:27017/test? authSource=admin');
Copy the code

I also want to connect to this remote database using the Mongodb Compass on my computer:

Modify the configuration file so that all IP addresses can connect

vim /etc/mongod.conf
Copy the code

Replace bindIp with 0.0.0.0 in the file

Net: port: 27017 bindIp: 0.0.0.0Copy the code

Open port 27017 of cloud server firewall:

Connect using mongodb Compass