1

Everytime I try to connect to my local MongoDB, I keep getting this Exception: SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 38748

Fun fact: the port in the exception increments by two after each try and is always wrong (I even started the server with the port throwing the exception next)

MongoDB server is running - I NETWORK [initandlisten] waiting for connections on port 27017

Dependency is set -

dependencies: mongo_dart: ^0.3.5 flutter: sdk: flutter

import 'package:mongo_dart/mongo_dart.dart' show Db, DbCollection;
class DBConnection {

  static DBConnection _instance;

  final String _host = "localhost";
  final String _port = "27017";
  final String _dbName = "debtservice";
  Db _db;

  static getInstance(){
    if(_instance == null) {
      _instance = DBConnection();
    }
    return _instance;
  }

  Future<Db> getConnection() async{
    if (_db == null){
      try {
        _db = Db(_getConnectionString());
        await _db.open();
      } catch(e){
        print(e);
      }
    }
    return _db;
  }

  _getConnectionString(){
    return "mongodb://$_host:$_port/$_dbName";
  }

  closeConnection() {
    _db.close();
  }

}

I already tried to run this code in plain dart and it runs.

Tunic
  • 79
  • 1
  • 9

3 Answers3

1

Ok, I fixed the problem now...

I had to take the Wireless LAN-Adapter IP of the my home device and start the mongodb with --bind_ip -ip-. The ip must also be provided in the connection string.

Still Thanks to MichaelM.

Tunic
  • 79
  • 1
  • 9
0

Your _host won't be localhost when running on a device or in an emulator - you'll need to specify the actual IP address or network host name of the computer MongoDB is running on.

MichaelM
  • 5,518
  • 2
  • 30
  • 23
  • I encountered the same problem when I used flutter with mongoDb, even i changed localhost to wifi ip address 192.168.1.1 see the ipconfig : IPv4 Address. . . . . . . . . . . : 192.168.1.4 Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : 192.168.1.1 – visulo Oct 30 '19 at 15:14
0

Update mongo config file

 sudo nano  /etc/mongod.conf

 bindIp:127.0.0.1 ##### replace this line with below 

 bindIP:0.0.0.0  #### 

After changing also, check the status of MongoDB

 sudo service mongod status

Now MongoDB works perfectly with flutter.

paul
  • 519
  • 6
  • 13