mongodb - MongoDB 在构建由 Vercel 托管的无服务器功能时,在用户信息部分中使用了未转义的斜杠
问题描述
我正在使用 Vercel 托管一个网站,内置 React 并通过它们提供无服务器功能。
我创建了一个使用 Mongoose 发布到我的 MongoDB 数据库的函数。
但是,我无法连接到我的数据库 - 它出现以下错误:
c5021f92-4dcc-49de-89c9-7a00203be4e0 ERROR Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"MongoParseError: Unescaped slash in userinfo section","reason":{"errorType":"MongoParseError","errorMessage":"Unescaped slash in userinfo section","name":"MongoParseError","stack":["MongoParseError: Unescaped slash in userinfo section"," at parseConnectionString (/var/task/node_modules/mongodb/lib/core/uri_parser.js:603:21)"," at QueryReqWrap.callback (/var/task/node_modules/mongodb/lib/core/uri_parser.js:114:7)"," at QueryReqWrap.onresolve [as oncomplete] (dns.js:205:10)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: MongoParseError: Unescaped slash in userinfo section"," at process.<anonymous> (/var/runtime/index.js:35:15)"," at process.emit (events.js:327:22)"," at processPromiseRejections (internal/process/promises.js:209:33)"," at processTicksAndRejections (internal/process/task_queues.js:98:32)"]}
Unknown application error occurred
在使用 Vercel 对环境变量和 MongoDB 进行了一些研究之后,我已经建立了这样的连接字符串。
mongoose.connect(`mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}@database.f9twk.mongodb.net/@otter-money?retryWrites=true&w=majority`, {useNewUrlParser: true});
我的问题是 a) 我在那个字符串中做错了什么?我正在使用模板文字,所以不确定它为什么不满意。b)有没有更好的方法来解决这个问题?
我已经在我的环境中尝试将完整的字符串作为 mongoURI,但没有运气。
解决方案
数据库名称中的“@”会使解析器感到困惑。你需要逃避它:
database.f9twk.mongodb.net/%40otter-money
更好的方法是传递连接参数options
:
mongoose.connect("mongodb+srv://database.f9twk.mongodb.net/",
{
useNewUrlParser: true,
user: process.env.MONGO_USER,
pass: process.env.MONGO_PASSWORD,
dbName: "@otter-money",
retryWrites: true,
w: "majority"
});
推荐阅读
- c# - 如何从数据库中获取数组中的数据?
- python - 在字符串 python 中查找带有额外字符的名称
- c++ - 如何确定相对于 x 轴像素范围的像素强度?
- sharepoint - 有没有办法在给定节点下的快速启动中添加 NavigationNode 而不是仅使用 Sharepoint Rest API 的子节点?
- javascript - 为什么在这个特定视图中输入的 onclick 事件不触发?
- webpack - Webpack - HMR 插件在 npm run build/dev 上抛出错误
- scala - 播放框架在启动后立即停止
- java - 在连续 8 次测量到的 GC 抖动后关闭 JVM
- java - 在片段中的 AsyncTask 中使用 Jsoup 获取网页元素(Android 新手)
- tensorflow - 如何在 Cleverhans 中导出 Facenet 的对抗样本?