I'm hosting a website with Vercel, built in React and with serverless functions through them.
I've created a function that posts to my MongoDB database using Mongoose.
However, I can't connect to my database - it comes up with the following error:
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
I've built my connection string like this, after doing some research into environment variables and MongoDB with Vercel.
mongoose.connect(`mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}@database.f9twk.mongodb.net/@otter-money?retryWrites=true&w=majority`, {useNewUrlParser: true});
My question is a) what am I doing wrong in that string? I'm using template literals so not sure why it's not happy with it. and b) is there a better way to approach this?
I've tried the full string as a mongoURI in my env, but no luck.
The '@' in the database name confuses the parser. You need to escape it:
The better way is to pass connection parameters in
options
: