【问题标题】:How to create a mongodb user for the first time in a Nodejs Application如何在 Nodejs 应用程序中首次创建 mongodb 用户
【发布时间】:2016-10-25 14:11:54
【问题描述】:

我在本地系统中使用 MongoDB 和 mongoose,其中 mongodbURL 没有用户名和密码。因此,当我使用语法运行它时,第一次创建数据库时使用了

 mongodb://localhost:27012/database

但现在我想为数据库使用用户名和密码,因此,我使用了给定的语法

   mongodb://username:password@localhost:27012/database

但我现在没有自动创建用户,脚本给了我一个身份验证失败错误

第一次应该如何创建用户?

【问题讨论】:

    标签: node.js mongodb authentication


    【解决方案1】:

    首先,使用 mongo shell 连接到您的数据库,无需身份验证。运行以下命令创建用户。

    db.createUser({
        user: "username",
        pwd: "password",
        roles: [
            { role: "readWrite", db: "database_name"}
        ]
    })
    

    您可能还想创建一个管理员,以便以后在启用身份验证时创建更多用户。

    db.createUser({
        user: "username",
        pwd: "password",
        roles: [
            "dbAdminAnyDatabase"
        ]
    })
    

    这些用户将在名为“admin”的数据库中创建。

    在此处查看所有 MongoDB 内置角色:https://docs.mongodb.com/v3.2/reference/built-in-roles/

    编辑你的 mongod 配置。如果您使用的是 YAML,请添加以下行:

    security:
      authorization: 'enabled'
    

    这里是 mongod 配置选项:https://docs.mongodb.com/v3.2/reference/configuration-options/

    如果您使用旧格式进行配置,请将身份验证设置为 true

    auth=true
    

    https://docs.mongodb.com/v2.4/reference/configuration-options/

    重启 mongod 并加载你的配置

    mongod --config ./mongodb.conf
    

    现在你应该可以连接 mongodb://username:password@localhost:27012/database

    【讨论】:

      【解决方案2】:

      您必须连接到您的数据库并启用身份验证。

      为此,您需要创建一个用户并设置一些权限。

      您可以参考以下文档: https://docs.mongodb.com/v3.2/tutorial/enable-authentication/

      希望对你有帮助:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多