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

标签 node.js mongodb mean-stack

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

module.exports = {
    DB: 'mongodb+srv://user%40gmail.com:%24ugar@cluster-jfgsm.mongodb.net/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 运行项目时,我在控制台中收到一条错误消息

Can not connect to the databaseMongoParseError: Unescaped at-sign in authority section

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

感谢任何帮助。 谢谢你

最佳答案

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

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

如果您的密码中有@,您应该将其更改为%40

关于node.js - 无法连接到数据库MongoParseError : Unescaped at-sign in authority section,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52632830/

相关文章:

python - 如何使用 python 的 mongoengine 检索不同集合中的记录?

node.js - 类型错误 : The "digest" argument is required and must not be undefined

arrays - Angular $save 并推送到数组项目后,除非我重新运行查询,否则不会添加

javascript - 为什么嵌入式下拉菜单只选择第一个选项?

javascript - 是否可以使用 Chrome 扩展在浏览器上运行 Node.js 模块

multithreading - node.js 应用程序中单进程中的多线程 socket.io

javascript - 我无法从 mongodb 检索值,即使它存在

html - 阻止 html 在代码块内呈现

Mongodb Gridfs 减少图像大小

mongodb - 如何在 mongoDB Compass 中运行 native mongo 查询?