在构建由Vercel托管的无服务器功能时,MongoDB在用户信息部分中使用非转义斜杠

时间:2020-10-07 07:19:52

标签: 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,但是没有运气。

1 个答案:

答案 0 :(得分:1)

数据库名称中的'@'会使解析器混乱。您需要对其进行转义:

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