Search code examples
node.jsmongodbloopbackjsmongodb-atlas

Loopback - Unable to connect to Mongo DB Atlas using mongodb+srv Protocol from loopback


Unable to connect to Mongo DB Atlas using mongodb+srv Protocol . while trying to query some data - MongoError: cannot do raw queries on admin in atlas

Connection Properties i tried in datasource.json

mongoDb: {
connector: 'mongodb',
name: 'mongoDb',
url:"mongodb+srv://#username:#password@cluster0-kvw6a.mongodb.net/test?retryWrites=true&w=majority"
}

while trying to query some data - getting this error

Unhandled error for request GET /api/Customers/getProfile?access_token=cMGG6C8fB8el0vbchpAzeOoTpH0N7Kf9va4b5k9Z6GrNAwgh4AtqQKlRYOyiWtsB: MongoError: cannot do
raw queries on admin in atlas
at Function.MongoError.create (C:\Users\User\Documents\GitHub\maharah\customer_server\node_modules\mongodb-core\lib\error.js:31:11)
at queryCallback (C:\Users\User\Documents\GitHub\maharah\customer_server\node_modules\mongodb-core\lib\cursor.js:212:36)
at C:\Users\User\Documents\GitHub\maharah\customer_server\node_modules\mongodb-core\lib\connection\pool.js:469:18
at process._tickCallback (internal/process/next_tick.js:61:11)

Connection Properties i tried in datasource.json

mongoDb: {
connector: 'mongodb',
name: 'mongoDb',
url:"mongodb+srv://#username:#password@cluster0-kvw6a.mongodb.net/test?
retryWrites=true&w=majority"
}

Solution

  • We have improved support for mongodb+srv protocol in April this year, see PR #497. You need to use loopback-connector-mongodb version 4.2.0 or newer.

    Quoting from README.md#using-the-mongodbsrv-protocol:

    MongoDB supports a protocol called mongodb+srv for connecting to replica sets without having to give the hostname of every server in the replica set. To use mongodb+srv as the protocol set the protocol connection property in the datasource.json to mongodb+srv. For example:

    "mydb": {
      "host": "myserver",
      "database": "test",
      "protocol": "mongodb+srv",
      "connector": "mongodb"
    }
    

    Note: the port is not specified when using the mongodb+srv protocol and will be ignored if given.