0
votes

I am implementing a MVC framework in Dart. I am implementing the find method and I want it to return the documents from that query.

The problem is that find() doesn't wait that the operation is performed and we need to bind a function inside then().

 static find(model, [params]){
     Db db = new Db("mongodb://127.0.0.1/dart");
     var models = [];
     db.open().then((o){
         return db.collection(model).find(params).forEach((d){
         models.add(d);
         });
     });
     return models;
}

Right now the return from find() is []. Do you know any way of returning the documents properly?

2
Well, that really doesn't solve my problem. I just want to get the documents return and not deciding on find what I am doing with every document. Please take a look in the Python Driver for example, about how simple is to do a find and then getting the documents just in time giantflyingsaucer.com/blog/?p=839 - André Freitas
when doing potentially long running calls like to a database, the execution is better when it is asynchronous, if you only want to continue after you have your data then you just put all your code in the `.then((_){/*in here*/}) callback for when the future completes. it's done like this so it doesnt lock up your program, if you do want to continue doing other stuff whilst the database is fetching data. - Daniel Robinson

2 Answers

2
votes
 static Future<List> find(model, [params]){
     Db db = new Db("mongodb://127.0.0.1/dart");
     var models = [];
     return db.open().then((o){
       db.collection(model).find(params).forEach((d){
         models.add(d);
       });
       return models;
     });
}

and use it like

find(model, [p1, p2, p3]).then((m) => ...);
2
votes

If synchronous API of your framework is absolute requirement for you, I'm afraid you are out of luck with mongo_dart. There is no way to build synchronous facade on top of asynchronous API and mongo_dart (or any other database driver in Dart AFAIK, see postgresql or sqljocky for example) is asynchronous.

Your experience with synchronous mongodb drivers in any other languages is not fully applicable here. Mongo_dart much more resemble mongodb driver for nodejs - asynchronous too. For nodejs async driver you too cannot get the result synchronously, see related questions:

Synchronous function calls for nodejs mongodb driver or What is the right way to make a synchronous MongoDB query in Node.js?

So I guess you should either embrace asynchronous code or return to python. Dart can do some things synchronously in the console applications but all the networking I believe is fully async here.