一步一步搭建react应用-mongodb开启身份认证

2017-09-13 14:54 出处:简书 人气: 评论(0

git地址

   mongod --port 3007  --config mongod.conf
use admin
db.createUser(
  {
    user: "myAdmin",
    pwd: "XXXXX",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)
    mongod --port 3007  --config mongod.conf --auth

连接时认证

mongo --port 3307 -u 'xxx' -p 'xxx' --authenticationDatabase "admin"

连接后认证

mongo --port 3307

use admin

db.auth('username','pwd')


use movies
db.createUser(
  {
    user: "moviesAdmin",
    pwd: "XXXX",
    roles: [ { role: "readWrite", db: "movies" },
             { role: "read", db: "db2" } ]
  }
)
//添加user moviesAdmin,对movies有读写权限,对db2有读权限

db.js

const {MongoClient,ObjectId} = require('mongodb')
const f = require('util').format
const user = encodeURIComponent('moviesAdmin')
const pwd = encodeURIComponent('xxxxx')
const authMechanism = 'DEFAULT'
let db_name='Movies'
if(process.env.NODE_ENV=='test'){
    db_name='Movies_test'
}
const url = f(`mongodb://%s:%s@localhost:3307/${db_name}?authMechanism=%s`, user, pwd, authMechanism)

module.exports = {
    connect() {
        return MongoClient.connect(url).catch(e=>{
            console.log(e)
        })
    },
    id(id) {
        try {
            if (id) {
                return new ObjectId(id)
            } else {
                return new ObjectId()
            }
        } catch (e) {

        }
    }
}

本文标签: constportmongodpwduserdb

相关文章

网站内容来源于互联网,仅供用于技术学习,请遵循相关法律 规,如有侵权,请联系管理员删除

Copyright © 2002-2017 JISHUX. 技术栈 版权所有

京ICP备15061484号-3