无法连接到数据库MongoParseError: Unescaped at-sign in authority section

问题描述 投票:0回答:8

我正在尝试连接到我的 nodeJS 项目中的 mongodb 服务器。我有一个数据库配置文件 DB.js

module.exports = {
    DB: 'mongodb+srv://user%40gmail.com:%[email protected]/test?retryWrites=true'
 };

用户名包含@ (%40) 标记,因为它是电子邮件 ID,密码包含 $(%24) 个字符。

我已经在我的 server.js 文件中将其连接为

    mongoose = require('mongoose'),
    config = require('./config/DB');

    const app = express();

    mongoose.Promise = global.Promise;
    mongoose.connect(config.DB,  { useNewUrlParser: true } ).then(
      () => {console.log('Database is connected') },
      err => { console.log('Can not connect to the database'+ err)}
    );

并且我在我的 package.json 文件中添加了自定义

serve
选项来运行 nodemon。

"scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "serve": "nodemon server.js"
  },

但是当我尝试使用命令

npm run serve
运行项目时,我在控制台中收到一条错误消息

无法连接到数据库MongoParseError: Unescaped at-sign in 权限部分

我也在堆栈溢出中搜索了很多问题,但对我没有任何帮助。

任何帮助表示赞赏。 谢谢

node.js mongodb mean-stack
8个回答
20
投票

像这样对密码进行编码是可以的:

const DB_USER = 'user';
const PASSWORD = encodeURIComponent('hello@123'); 
const DB_URL = `mongodb://${DB_USER}:${PASSWORD}@ds331735.mlab.com:31772/any_db`;

如果您的密码中有

@
,请将其更改为
%40


2
投票

发现了同样的问题,但毕竟不是登录所需的mongodb atlas帐户用户(用户名是email)。

需要的用户是可以访问在 mongodb atlas 中创建的集群的用户。

Project > clusters > [Select cluster]

Security tab > select/create new db user

这些用户不需要有特殊字符(甚至有一条消息表明这些字符将被编码)

见下图:


1
投票
const dbName = 'your db name';
const dbUser = 'your db username';
const dbPassword = 'your db user password';

const MONGODB_URI = `mongodb://${dbUser}:${dbPassword}@ds047207.mlab.com:47207/${dbName}`;

注意:@ds047207.mlab.com:47207 它会在您的帐户支票中提供给您。 它没有连接尝试简单的用户名和密码。创建用户前: 用户名:asif,密码:asif123 Bcoz 我已经创建了用户名:asif-vora 和密码:asif@1234 当我尝试使用用户名:asif,密码:asif123 时它在数据库连接中出现错误它的工作正常:)


0
投票

你试过转义@和$ like

mongodb+srv://user\@gmail.com:\[email protected]/test?retryWrites=true

0
投票

试试这个它和我一起工作:

DB: mongodb://admin:<password>@nerdstore-shard-00-00-4iypj.mongodb.net:27017,nerdstore-shard-00-01-4iypj.mongodb.net:27017,nerdstore-shard-00-02-4iypj.mongodb.net:27017/nerdstore?ssl=true&replicaSet=nerdstore-shard-0&authSource=admin&retryWrites=true&w=majority

用你的碎片改变它。


0
投票

如果您的用户名和密码有任何这些特殊字符

/ ? # [ ] @

您在通过命令行界面连接或运行命令时可能会遇到问题:/ ? # [ ] @ 在您的 URI 中使用等效的 ASCII 编码。对于 @ 等价于 %40


0
投票

这个问题来自你的 mongoDB password。如果将密码作为字符串提供,您将遇到此[在此处输入图片描述][1] 问题。所以在mongoDB atlas中创建用户时点击自动生成密码。

像图集里的下图

https://www.mongodb.com/docs/guides/images/db-user-password.png


-2
投票

非常简单的解决方案: 从密码中删除特殊字符:

我也面临问题。我的密码是@。

解决方案:数据库访问->它将显示您的用户,单击编辑并更新没有特殊字符的新密码。 然后在你的连接字符串中使用它。

© www.soinside.com 2019 - 2024. All rights reserved.