Mongodb 使用 Mongoose 的安全服务器设置

Mongodb Secure Server Setup with Mongoose

我试图成功的设置是有一个创建数据库的节点进程,其他服务器以安全的方式访问这些数据库。
所以我的想法是使用用户从节点创建数据库并通过。然后打开服务器mongodb端口开启访问,锁定mongoadmin用户。如果那个理论是好的:

  1. 如何使用户具有 mongoose,以便只有该用户才能访问数据库?
  2. /etc/mongodb.conf 上我应该只添加 bind_ip = 0.0.0.0 吗?

PS:我正在使用 Ubuntu 16:04 和最新的 Mongodb。

编辑:2017 年 8 月 13 日
到目前为止我取得的成功是 addUser = db.createUser({user: "admin",pwd: "admin",roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]}); 用于管理数据库,在数据库处于 --auth 下时连接它并尝试通过该连接创建其他数据库,如下所示。

var adminConnection = mongoose.createConnection('mongodb://admin:admin@localhost:27017/admin', {
    useMongoClient: true
});
console.log(typeof adminConnection.db.executeDbAdminCommand);//function
Your  /etc/mongod.conf  YAML file will be look like this

storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log


# network interfaces  put your ip in bindIp in form of Array like below
net:
  port: 27017
  bindIp: [127.0.0.1,84.20.57.18]

#before enabling security authorization you must add mongodb database user
security:
  authorization: "enabled"

#Replication oplogsize mb set based on Main Memory of your Ubuntu Server (It will be good to set 1024 for speed of database Operation). In replSetName give your Replica set name or your Project Name Ex: smartcity
replication:
  oplogSizeMB: 1024
  replSetName: "smartcity"

在节点 js 中如何使用 mongoose 和连接到你的 mongodb 数据库如下

var mongoose = require('mongoose');
var options = {
    useMongoClient:true
};
var dbUrl = 'mongodb://<dbusername>:<dbpassword>@<db-ipaddress>:27017/<dbname>?replicaSet=<replicasetname>';//Ex:"mongodb://smartcityUser:smartcity1234@84.20.57.18:27017/smartcity?replicaSet=smartcity"

mongoose.connect(dbUrl,options);
mongoose.Promise = global.Promise;

愿我的工作能解决您的问题,祝一切顺利

总的来说,我几乎做到了我想做的。这是解决方案。

var a_conn = mongoose.createConnection('mongodb://admin:admin@localhost:27017/admin', {
    useMongoClient: true
});
a_conn.once('open', function() {
    a_conn.useDb('w_one');
    a_conn.otherDbs[0].db.addUser('user', 'pass', {
        db: 'w_one',
        roles: ["readWrite"]
    });
    var Schema = mongoose.Schema({});
    var Collection = a_conn.otherDbs[0].model('cool', Schema, 'cool');
    var doc = new Collection({});
    doc.save(function() {
        doc.remove(function() {
            var testConn = mongoose.createConnection('mongodb://user:pass@localhost:27017/w_one', {
                useMongoClient: true
            });
            testConn.once('open', function() {
                //Collection.collection.drop('cool');
                console.log('Database is ready.');
            });
        });
    });
});

一般我都是用文档创建集合来创建数据库,当我删除那个集合时,数据库会自动删除,如果有不删除它的选项,那将是解决方案的一个很好的改进。