2

In a nodeJS app, I'd want to connect to my MongoDB database via its UNIX socket /tmp/mongdb-27017.sock. I use the package https://mongodb.github.io/node-mongodb-native/?jmp=docs (version 3.1.6), this way:

const client = await MongoClient.connect("mongodb://%2Ftmp%2Fmongodb-27017.sock")

The URI is referenced in the doc here: https://docs.mongodb.com/manual/reference/connection-string/#unix-domain-socket. But in my case it fails with the error:

MongoNetworkError: failed to connect to server [/tmp/mongodb-27017.sock:27017] on first connect [MongoNetworkError: connect ECONNREFUSED /tmp/mongodb-27017.sock]

Do anyone know if it's possible to connect to a mongoDB UNIX socket from nodeJS, and if there's something specific to do? Couldn't find specific info in the doc.

2 Answers 2

3

For me the solution was not to escape the path, contrary to the documentation on docs.mongodb.com. So try

mongodb:///tmp/mongodb-27017.sock

instead of

mongodb://%2Ftmp%2Fmongodb-27017.sock

And of course make sure the socket file exists:

$ ls -al /tmp/mongodb-27017.sock
srwxrwxrwx 1 mongodb mongodb 0 Apr 1 21:47 /tmp/mongodb-27017.sock

A more complete example using a user account from another database then the one we're connecting to:

mongodb://foo:pass@/tmp/mongodb-27017.sock/somedb?authSource=admin

Here a connection is made to the somedb database, by user foo which is a user account stored in the admin database.

Sign up to request clarification or add additional context in comments.

1 Comment

I had also tried this. It returns the same error. My issue is likely to be related to the fact that in my case this socket is a Docker mounted volume (even if I usually don't have troubles with sockets mounted this way). It doesn't matter anymore, I have another way to connect. Thanks for trying!
0

It is possible by using the full Unix domain socket paths instead of hostname on which mongod should listen for client connections. It started in Mongo 3.6

1 Comment

I know. My question is about connecting by using Unix sockets from nodeJS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.