【MongoDB】【错误记录】添加账号成功,但是连接失败。(原因为创建用户时未切换数据库)

    科技2026-08-29  5

    原因:创建用户时,为切换到对应的数据库。用户都创建到了admin(默认数据库)下了。 出错情况记录:

    新增了一个数据库xxx, 创建了新用户,权限是读写xxx数据库(添加时的对应数据库是admin)。 db.createUser({ user: 'test', pwd: '123456',roles:[{ role: 'readWrite', db: 'xxx' }] })

    错误内容

    MongoDB shell version v4.4.1 connecting to: mongodb://localhost:27017/?authSource=root&compressors=disabled&gssapiServiceName=mongodb Error: Authentication failed. : connect@src/mongo/shell/mongo.js:374:17 @(connect):2:6 exception: connect failed exiting with code 1

    解决方法

    连接root用户 use xxx db.createUser({ user: 'test', pwd: '123456',roles:[{ role: 'readWrite', db: 'xxx' }] }) 搞定
    Processed: 0.016, SQL: 9