gpt4 book ai didi

mongodb - Dart使用MongoDB进行强类型输入

转载 作者:行者123 更新时间:2023-12-03 03:29:38 25 4
gpt4 key购买 nike

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

最佳答案

也许Objectory很适合您。

从自述文件:

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

来自object_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);

}

查看 Quick tour,样本和测试以获取更多信息

关于mongodb - Dart使用MongoDB进行强类型输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14014072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com