[转] Node.js使用MongoDB3.4+Access control is not enabled for the database解决方案

今天使用MongoDB时遇到了一些问题

建立数据库连接时出现了warnings

出现这个警告的原因是新版本的MongDB为了让我们创建一个安全的数据库 
必须要进行验证 
后来在外网找到了答案

解决方案如下:

创建管理员

use admin
db.createUser(
  {
    user: "userAdmin", //用户名
    pwd: "123", //密码
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] //权限
  }
)

 

重启MongoDB服务器

mongod --auth --port 27017 --dbpath <关联路径>

 

(端口默认就是27017可以不指定) 

终端最后输出"[initandlisten] waiting for connections on port 27017"
启动完成

连接并认证

mongo --port 27017 -u "userAdmin" -p "123" --authenticationDatabase "admin"

 

添加额外权限用户

use test
db.createUser(
  {
    user: "tester",
    pwd: "123",
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)

 

mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"

 


MongoDB更新了,使用mongoose也不能简单的建立连接了 
必须要添加必要参数

var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'test', 27017, {user: 'tester', pass: '123'});

posted @ 2018-06-05 21:52  {前端开发}  阅读(1144)  评论(0编辑  收藏  举报