我想使用 dart 在 mongodb 实例上创建一个漂亮而简单的层,但我无法做到:
给定一个 mongodb 实例 "test-mongo-layer" :
蒙戈壳:
使用 test-mongo-layer 切换到 db test-mongo-layer db.users.find() { "_id" : ObjectId("524b1bf8fbfe21c9c4cdb772"), "name" : "Toto", "login" : "toto" } { “_id”:ObjectId(“524b1bf8fbfe21c9c4cdb772”),“名称”:“Titi”,“登录”:“titi”}
还有一个 model.dart 源文件:
class User {
String name;
String login;
User(this.name, this.login)
User.fromJson(Map map) {
name = map['name'];
login = map['login'];
}
}
还有一个 persistence.dart 源文件:
import 'package:mongo_dart/mongo_dart.dart';
import '../lib/model.dart';
class PersistenceLayer{
Db _mongodb;
PersistenceLayer(this._mongodb)
List<User> getUsers() {
List<User> users = new List();
_mongodb.open().then((o){
return __mongodb.collection('users').find().forEach((jsonUser){
User user = new User.fromJson(jsonUser);
users.add(user);
});
}).then((jsonUsers){
_mongodb.close();
});
return users;
}
}
当我启动以下测试时:
import 'package:mongo_dart/mongo_dart.dart';
import 'package:unittest/unittest.dart';
import '../lib/model.dart' ;
import '../lib/persistence.dart' ;
main() {
Db db = new Db("mongodb://127.0.0.1/test-mongo-layer");
test('Test get users', () {
PersistenceLayer persistence = new PersistenceLayer(db);
var users = persistence.getUsers();
expect(users.length, 2);
}
}
然后出现异常:
未捕获的错误:预期:<2> 实际:<0><
这很简单,但它不起作用,我必须弄乱未来,因为当我在调试时执行它时甚至没有执行代码......
解决方案:感谢亚历山大
persistence.dart 源文件:
Future<List<User>> getUsers() {
List<User> users = new List();
return _mongodb.open()
.then((_){
return _mongodb.collection('users').find().forEach((jsonUser){
User user = new User.fromJson(jsonUser);
users.add(user);
});
})
.then((_) {
return users;
})
.whenComplete((){
_mongodb.close();
});
}
测试 :
test('Test get users', () {
PersistenceLayer persitence = new MongoPersistence(db);
Future<List<User>> usersFuture = persistence.getUsers();
usersFuture.then((users) => expect(users.length, 2) );
});