cannot connect to mogodb with database name
mustafat0k
HOBBYOP

2 months ago

It seems caused by service becacause connecting to it with mongo atlas is flawless

but mongodb service in railway doesnt connect like that way with database name

`mongodb://<name>:<pass>@mongodb.railway.internal:27017/<dbname>?retryWrites=true&w=majority`

without db name creating default as test

Solved$10 Bounty

Pinned Solution

ilyassbreth
FREE

2 months ago

your solution is correct, that's the right way to do it with railway's mongodb

the issue is railway's mongo authenticates against the admin database by default. when you put the db name in the url like /dbname, it tries to auth against that database instead and fails.

two ways to fix this:

  1. your way (better): connect without dbname in url, pass it as option {dbName: 'yourdb'}

  2. or add ?authSource=admin to your connection string: mongodb://user:pass@host:27017/dbname?authSource=admin&retryWrites=true&w=majority

your solution with the dbname option is cleaner though, stick with that

2 Replies

mustafat0k
HOBBYOP

2 months ago

This solution is worked. In normal conditions first method also should work but somehow doesn't log in.

https://stackoverflow.com/a/74420142/32123247

const url = "mongodb://127.0.0.1:27017"

mongoose.connect(url,{
    dbName: 'DatabaseName',
}).then(() => {
    console.log("Connected to Database");
}).catch((err) => {
    console.log("Not Connected to Database ERROR! ", err);
});

ilyassbreth
FREE

2 months ago

your solution is correct, that's the right way to do it with railway's mongodb

the issue is railway's mongo authenticates against the admin database by default. when you put the db name in the url like /dbname, it tries to auth against that database instead and fails.

two ways to fix this:

  1. your way (better): connect without dbname in url, pass it as option {dbName: 'yourdb'}

  2. or add ?authSource=admin to your connection string: mongodb://user:pass@host:27017/dbname?authSource=admin&retryWrites=true&w=majority

your solution with the dbname option is cleaner though, stick with that


Status changed to Solved brody 2 months ago


Loading...