Connect to MongoDB Atlas with mongo_dart

1.7k Views Asked by At

I try to connect to a MongoDB Atlas database through mongo_dart with this line of code. The provided link from MongoDB is defined by:

mongodb+srv://<user>:<PASSWORD>@test-asdf.mongodb.net/test?retryWrites=true

throws an "Invalid scheme" Error. When I cut out "+srv" and try to connect with:

Db db = new Db("mongodb://<user>:<password>@test-asdf.mongodb.net/test?retryWrites=true");

it throws a SocketException: Failed host lookup.

Is it even possible to access to a atlas mongoDB or am I forgetting something?

2

There are 2 best solutions below

0
On

The mongodb+srv:// protocol is for new driver, maybe you can try to click the button "I am using driver 3.4 or earlier" to get the legacy url with mongodb:// protocol

0
On

In order to connect to atlas, you need to pass connection string which connect your atlas to mongo_dart like this:

import "package:mongo_dart/mongo_dart.dart;

  void getConnection() async {
     String connectionString = "mongodb+srv://<user>:<password>@test-asdf.mongodb.net/test?retryWrites=true&w=majority";
        print(connectionString);
        // Connect to database:
        Db db = await Db.create(connectionString);
        await db.open();
        print(db);

  
}