下载mongodb
yum安装
vi /etc/yum.repos.d/mongodb-org-4.2.repo
[mongodb-org-4.2]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc
yum install -y mongodb-org
修改配置文件
cd /etc/mongod.conf
# network interfaces
net:
port: 27017
bindIp: 0.0.0.0 # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.
maxIncomingConnections: 100
#security:
security:
authorization: enabled // 创建用户后开启权限
#operationProfiling:
启动可能报错
Job for mongod.service failed because the control process exited with error code. See "systemctl status mongod.service" and "journalctl -xe" for details.
1. 权限问题
cd /tmp/
chown mongod:mongod mongodb-27017.sock
2. YAML配置问题
cd /etc/mongod.conf
创建admin用户
use admin
db.createUser({user:"admin",pwd:"admin",roles:[{ role: "userAdminAnyDatabase", db: "admin" }]})
开启权限认证后创建数据库/用户
## 配置文件
#security:
security:
authorization: enabled // 创建用户后开启权限
db.auth(账号,密码)
use 新建的数据库
db.createUser(
{
user: "username",
pwd: "password",
roles: [ { role: "readWrite", db: "新建的数据库" } ]
}
);
node连接
-
yarn add mongodb
-
建立连接
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://用户名:密码@ip地址:27017/数据库名';
MongoClient.connect(url, function (err, db) {
if (err) {
console.error(err);
return;
} else {
console.log('Connected correctly to server');
var dbase = db.db('数据库名');
dbase.collection("user").insertOne({username: 'test', password: 'test'}, function(err, res) {
if (err) throw err;
console.log('插入成功');
db.close();
})
}
});