首页 > 解决方案 > 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,但没有运气。

标签: mongodbvercel

解决方案


数据库名称中的“@”会使解析器感到困惑。你需要逃避它:

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"
});

推荐阅读