I am working on a Meteor project, and I have to say that this is not easy, especially for one thing: callbacks!
Everything is asynchronous, so I wonder how should I do to get the results from my mongodb.
var user = Meteor.users.findOne({username: "john"}); return (user);
...
var user = Meteor.users.findOne({username: "john"}); if (user) // so ok, I check if it exists! return (user); // Cool, I got my user! return (); // Ok and what should I return here? I want my user!
I do not want to be dirty and set like setTimeout everywhere. Does anyone have a solution for this?
EDIT: I noticed in router.js with console.log that my data is returned 4 times. 2 times with the value undefined and 2 more times with the expected value. Apparently, it is still undefined. Why does the router go 4 times in this route? Does it display the first result of the return value in the router?
What should I return if find () did not find anything?
EDIT 2: Below is the code for understanding.
this.route('profilePage', { path: 'profil/:_id?', waitOn: function() { return [ Meteor.subscribe('article', { prop: this.params._id}), // id can be id or username Meteor.subscribe('article', { userId: this.params._id}), // id can be id or username Meteor.subscribe('params'), Meteor.subscribe('profil', (this.params._id ? this.params._id : Meteor.userId())) ]; }, data: function() { if (this.params._id) { var user = Meteor.users.findOne(this.params._id); if (!user) user = Meteor.users.findOne({username: this.params._id}); console.log(user); return user; } else if (Meteor.userId()) return Meteor.user(); else Router.go("userCreate"); } });
I get this on the console: http://puu.sh/debdJ/69419911f7.png
(text version)
undefined undefined Object_id: "o3mgLcechYTtHPELh"addresses: (....) Object_id: "o3mgLcechYTtHPELh"addresses: (....)