[开发问题]MongoDB开发问题集

1.0 Access control is not enabled for the database.

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

重启数据库服务器,有是有会出现有另外一个程序正在使用mongodb,可以手动停止mongoDB server,之后在运行

 mongod --auth --port 27017 --dbpath D:\Applications\MongoDB\data

连接并认证

mongo --port 27017 -u "root" -p "123456" --authenticationDatabase "admin"

2.0认证过程出现的错误

 Unauthorized: not authorized on admin to execute command { getLog: "startupWarnings", lsid: { id: UUID("3f1dc810-2da6-4bec-8399-01076f23e4f6") }, $db: "admin" }

执行以下命令

 use admin
db.stats()
{
        "ok" : 0,
        "errmsg" : "not authorized on admin to execute command { dbstats: 1.0, scale: undefined, lsid: { id: UUID(\"44ed842d-68c2-41c8-8232-bf91a9084e19\") }, $db: \"admin\" }",
        "code" : 13,
        "codeName" : "Unauthorized"
}
 db.auth("root","123456")
db.grantRolesToUser("root",[{role:"read",db:"admin"}])

现在运行db.stats()就不会出现以上问题

 db.stats()
{
        "db" : "admin",
        "collections" : 2,
        "views" : 0,
        "objects" : 4,
        "avgObjSize" : 313.25,
        "dataSize" : 1253,
        "storageSize" : 69632,
        "numExtents" : 0,
        "indexes" : 3,
        "indexSize" : 69632,
        "fsUsedSize" : 144521494528,
        "fsTotalSize" : 166431027200,
        "ok" : 1
}

3.0 数据查找报错

[MongoDB在github上的解答]
(https://github.com/Automattic/mongoose/issues/4067)

Error: error: {
        "ok" : 0,
        "errmsg" : "Projection cannot have a mix of inclusion and exclusion.",
        "code" : 2,
        "codeName" : "BadValue"
}

除了 _id 你不能在一个对象中同时指定 0 和 1,如果你设置了一个字段为 0,则其他都为 1,反之亦然。

4.0 数据库连接错误 { useNewUrlParser: true }

(node:135164) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.

const Koa =  require("koa");
const Router = require("koa-router");
const MongoClient = require("mongodb").MongoClient;

const MongoConf = require("./MongoDBConfig");

// 这是个异步函数
console.time("MongoDBConnectTime");
MongoClient.connect(MongoConf.DbUrl,{ useNewUrlParser: true },(err,client)=>{
  if(err){
      console.log("数据库连接失败");
      return ;
  }
  const db = client.db(MongoConf.dbName);

  db.collection("users").insertOne({"name":"username","age":25},function(err,result){
      if(err){
          console.log("插入数据失败");

      }
      console.log(result);
      db.close();
      console.timeEnd("MongoDBConnectTime");

  });
})

5.0 MongoDB系统配置

mongod --config D:\Applications\MongoDB\bin\mongod.cfg

I CONTROL [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify –sslDisabledProtocols ‘none

慕课网上也有出现过同样的问题,得知的结果可能是配置文件出的问题,然后我直接输入在终端直接输入mongod,出现以下报错

exception in initAndListen: NonExistentPath: Data directory D:\data\db\ not found., terminating
后来直接重新配置data路径

mongod --auth --port 27017 --dbpath D:\Applications\MongoDB\data

又报如下错误

2018-12-13T12:03:38.146+0800 I STORAGE [initandlisten] exception in initAndListen: DBPathInUse: Unable to create/open the lock file: D:\Applications\MongoDB\data\mongod.lock (另一个程序正在使用此文件,进程无法访问。).
手动关闭服务后重新配置,运行mongod正常

6.0 MongoDB权限配置问题

创建超级管理员

use admin
db.createUser({
    user:'admin',
    pwd:'123456',
    roles:[{role:'root',db:'admin'}]
})

开启权限配置

D:\Applications\MongoDB\bin\mongod.cfg
security:
  authorization: enabled

重启服务

6.0.1 db.auth失败
在正确开启权限认证 的情况下,终端直接输入mongo

《[开发问题]MongoDB开发问题集》 mongoDB权限认证问题.jpg

> db.auth("admin","123456")
Error: Authentication failed.
0//权限认证失败
>

原因是没有具体设置那个数据库的权限认证

mongo 数据库名字
eg:C:\WINDOWS\system32>mongo admin 

Robo 3T可视化工具连接错误

当我们通过ROobo3T连接mongoDB的时候出现如下问题

Failed to execute "listdatabases" command.

解决方案(前提是你之前mongoDB已经开启认证)

《[开发问题]MongoDB开发问题集》 Robo 3TMongoDB数据库连接错误解决方案.jpg

MongoDB创建用户出错

 Error: couldn't add user: No role named root@mmiroot

情景再现:创建了mmidb数据库之后,在admin数据库下想为mmidb数据库创建一个root用户。之后就出现上述问题。

网上查询得知对于非 admin 库,不能拥有root, clusterAdmin、readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase 这些角色。

db.createUser({
... "user": "mmiroot",
... "pwd": "sagerealmmi",
... "roles": [ {role: "dbOwner", db: "mmidb"}]
... })

Successfully added user: {
        "user" : "mmiroot",
        "roles" : [
                {
                        "role" : "dbOwner",
                        "db" : "mmidb"
                }
        ]
}

mongoose在koa中获取数据无法返回给前端

router.post("/reg",async(ctx,next)=>{
     
    let postJson = await Tools.parsePostData(ctx);
    console.log(postJson);
    var user = new UserModel({
        uEmail:postJson.uName,
        uPwd:Utils.MD5Crypto(postJson.uPwd)
    });
    var saveResult = await user.save(function(err,doc){
        if(err){
            console.log(err)
        }
        ctx.body = dco
    });
    next();

});

上面的方法前端所得到的结果是一个404,究其原因还是因为save操作是一个异步请求,解决方案:

router.post("reg",async(ctx,next)=>{
    let postJson = await Tools.parsePostData(ctx);
    var user = new UserModel({
        uEmail:postJson.uName,
        uPwd:Utils.MD5Crypto(postJson.uPwd)
    });
    var saveUser = await user.save()
               .then((res)=>{
                    return res;
               })
               .catch((err)=>{
                    return err;
               });
  ctx.body = saveUser;
});
    原文作者:1024俱乐部
    原文地址: https://www.jianshu.com/p/9a3008435594
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞