4 months ago
I'm trying to connect to a MongoDB deployed in Railway from an express server also deployed in Railway.
To do it, I set up an env variable in the server with the (ref) value ${{ MongoDB.MONGO_URL }}
In the server, I try to connect using mongoose in the standard way:
mongoose
.connect(
`${process.env.MONGO_URL_REF}/wanderjoy`
)
.then(() => console.log("Connected to MongoDB"))
.catch((err) => console.error("MongoDB connection error:", err));
(where "wanderjoy" is the db name)
In the logs, I see the following error:
MongoDB connection error: MongoServerError: Authentication failed.
at Connection.onMessage (/app/node_modules/mongodb/lib/cmap/connection.js:202:26)
at MessageStream.<anonymous> (/app/node_modules/mongodb/lib/cmap/connection.js:61:60)
at MessageStream.emit (node:events:518:28)
at processIncomingData (/app/node_modules/mongodb/lib/cmap/message_stream.js:124:16)
at MessageStream._write (/app/node_modules/mongodb/lib/cmap/message_stream.js:33:9)
at writeOrBuffer (node:internal/streams/writable:572:12)
at _write (node:internal/streams/writable:501:10)
at Writable.write (node:internal/streams/writable:510:10)
at Socket.ondata (node:internal/streams/readable:1009:22)
at Socket.emit (node:events:518:28) {
ok: 0,
code: 18,
codeName: 'AuthenticationFailed',
connectionGeneration: 0,
[Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }
}
In the server, I tried logging the env variable and I verified in the logs that it has the correct value.
Why is it failing at authenticating?
I've also tried connecting to the DB from my local machine, this time using MongoDB's Connection URL (as given by the UI when clicking on "Connect -> Public Network" and I get the same error.
How could I fix it?
Thank you
Project (it is not mine, I'm a collaborator, so I cannot link it in the "Project" field) : https://railway.com/project/0c666f59-f99f-446c-9748-3f5307856106?environmentId=20e7b1fe-5bf4-4f17-8e52-2ba606ff7cbe
2 Replies
4 months ago
Apologies but this looks like an issue with the application level code. Due to volume, we can only answer platform level issues here
Leaving this thread open to the public but you likely should verifying the MongoDB credentials (username and password) used in the connection string. Ensure that the credentials are correctly set in the environment variables and that they match the ones configured in the MongoDB instance on Railway.
Status changed to Awaiting User Response Railway • 4 months ago
4 months ago
Hey, I'm the owner of the project we are collaborating in. For the next one encountaring this issue here's the solution:
Remove the database name from the url and add it in the options object:
mongoose
.connect(
`${process.env.MONGO_URL_REF}`,
{
dbName: "myDbName",
}
)
.then(() => console.log("Connected to MongoDB"))
.catch((err) => console.error("MongoDB connection error:", err));
Cheers!