1

取自 mongo_dart 的 blog.dart 中的示例,我想在将记录添加到数据库时添加一些强类型。任何帮助表示赞赏。

  Db db = new Db("mongodb://127.0.0.1/mongo_dart-blog");
  DbCollection collection;
  DbCollection articlesCollection;
  Map<String,Map> authors = new Map<String,Map>();
  db.open().chain((o){
    db.drop();
    collection = db.collection('authors');
    collection.insertAll( //would like strongly typed List here instead
      [{'name':'William Shakespeare', 'email':'william@shakespeare.com', 'age':587},
      {'name':'Jorge Luis Borges', 'email':'jorge@borges.com', 'age':123}]
    );
    return collection.find().each((v){authors[v["name"]] = v;});
  }).chain((v){
    print(">> Authors ordered by age ascending");
    db.ensureIndex('authors', key: 'age');
    return collection.find(where.sortBy('age')).each(
      (auth)=>print("[${auth['name']}]:[${auth['email']}]:[${auth['age']}]"));
  }).then((dummy){
    db.close();
  });
4

1 回答 1

2

也许Objectory会适合你。

来自自述文件:

Objectory - 用于服务器端和客户端 Dart 应用程序的对象文档映射器。Objectory 提供类型化、检查的环境来建模、保存和查询持久在 MongoDb 上的数据。

objectory 中 blog_console.dart 示例的相应片段如下所示:

 objectory = new ObjectoryDirectConnectionImpl(Uri,registerClasses,true);
  var authors = new Map<String,Author>();
  var users = new Map<String,User>();  
  objectory.initDomainModel().chain((_) {
    print("===================================================================================");
    print(">> Adding Authors");
    var author = new Author();
    author.name = 'William Shakespeare';
    author.email = 'william@shakespeare.com';
    author.age = 587;
    author.save();
    author = new Author();
    author.name = 'Jorge Luis Borges';
    author.email = 'jorge@borges.com';
    author.age = 123;
    author.save();    
    return objectory.find($Author.sortBy('age'));
  }).chain((auths){  
    print("============================================");
    print(">> Authors ordered by age ascending");
    for (var auth in auths) {
      authors[auth.name] = auth;
      print("[${auth.name}]:[${auth.email}]:[${auth.age}]");
    }
........

Author 类定义为:

class Author extends PersistentObject  {
  String get name => getProperty('name');
  set name(String value) => setProperty('name',value);

  String get email => getProperty('email');
  set email(String value) => setProperty('email',value);

  int get age => getProperty('age');
  set age(int value) => setProperty('age',value);

}

查看快速浏览、样品和测试以获取更多信息

于 2012-12-24T06:46:57.123 回答