import 'package:EasyDartModule/base/database/DataBase.dart'; import 'package:mongo_dart/mongo_dart.dart'; class MongoDb implements DataBase { final DataBaseConfig config; final Db db; MongoDb(this.config) : db = Db( "mongodb://${config.userName}:${config.password}@${config.host}/${config.dataBase}?authSource=admin") { connect(false); } bool isConnected() { return db.isConnected; } void connect(reconnect) { if (reconnect) { print("尝试重连MongoDb"); } Future.delayed(Duration(seconds: 1), () async { try { await db.open(); print('MongoDb Connected successfully!'); //定时检测数据库是否断开 do { await Future.delayed(Duration(seconds: 5)); } while (db.isConnected); connect(true); } catch (e) { print('MongoDb Connection error: $e'); connect(reconnect); } }); } DbCollection getCollection(String name) { return db.collection(name); } @override Future delete(String table, dynamic condition) async { await getCollection(table).deleteMany(condition); } @override Future insert(String table, Map data) async { await getCollection(table).insert(data); } @override Future>> query(String table, {dynamic condition}) async { if (condition == null) { return await getCollection(table).find().toList(); } if (condition is AggregationPipelineBuilder) { return await getCollection(table) .aggregateToStream(condition.build()) .toList(); } else { return await getCollection(table).find(condition).toList(); } } @override Future update( String table, Map data, dynamic condition, {bool multiUpdate = false}) async { await getCollection(table) .update(condition, data, multiUpdate: multiUpdate); } @override Future count(String tbale, {dynamic condition}) async { return await getCollection(tbale).count(condition); } }