是否可以使用 flutter dart 连接到本地 MongoDB?

Is it possible to connect to local MongoDB with flutter dart?

每次我尝试连接到本地 MongoDB 时,我都会收到此异常: SocketException:OS 错误:连接被拒绝,errno = 111,地址 = localhost,端口 = 38748

有趣的事实:异常中的端口在每次尝试后递增 2,并且总是错误的(我什至启动服务器时端口接下来会抛出异常)

MongoDB 服务器正在 运行ning - I NETWORK [initandlisten] 等待端口 27017 上的连接

依赖设置 -

依赖项: mongo_dart: ^0.3.5 扑: SDK: 颤动

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();
  }

}

我已经尝试 运行 将此代码用简单的 dart 和它 运行s.

当 运行 在设备或模拟器中时,您的 _host 将不是本地主机 - 您需要指定计算机的实际 IP 地址或网络主机名 MongoDB 运行 开启。

好的,我现在解决了问题...

我必须使用我的家庭设备的无线 LAN-Adapter IP 并使用 --bind_ip -ip- 启动 mongodb。还必须在连接字符串中提供 ip。

还是感谢MichaelM。

更新mongo配置文件

 sudo nano  /etc/mongod.conf

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

 bindIP:0.0.0.0  #### 

同样更改后,检查MongoDB

的状态
 sudo service mongod status

现在 MongoDB 与 flutter 完美配合。