arvymetal
arvymetal

Reputation: 3254

NodeJS MongoDB UNIX socket connection

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.

Upvotes: 2

Views: 1628

Answers (2)

Tim
Tim

Reputation: 31

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.

Upvotes: 3

xolile Xaba
xolile Xaba

Reputation: 1

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

Upvotes: 0

Related Questions