Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor - no more callbacks for "findOne" function

Tags:

mongodb

meteor

i'm working on a Meteor project, and I must say that isn't easy at all, especially for one thing: callbacks !

Everything is async, so I wonder how do I must do to get results from my mongodb.

var user = Meteor.users.findOne({username: "john"});
return (user); // sometimes returns "undefined"

...

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 don't want to be dirty and put like setTimeout everywhere. Anybody has a solution for this ?


EDIT : I noticed in router.js with console.log that my data is returned 4 times. 2 times with an undefined value and 2 other times with the expected value. In the view, it's still undefined. Why the router passes like 4 times in this route ? Does it display the first result of the return value in the router ?

What should I return if the find() doesn't find anything ?


EDIT 2: Here is some code to understand.

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 following)

undefined
undefined
Object_id: "o3mgLcechYTtHPELh"addresses: (....)
Object_id: "o3mgLcechYTtHPELh"addresses: (....)
like image 534
Sw0ut Avatar asked Dec 01 '14 19:12

Sw0ut


1 Answers

findOne(yourId) is a sync method which is equivalent to find({ _id: yourId}, callback). The difference is that find() allows you to define a callback. If you don't pass a callback to find() this method will be sync.

check wrapAsync: http://docs.meteor.com/#/full/meteor_wrapasync It allows you to code in a sync style with a async operations.

Free lesson on EventedMind: https://www.eventedmind.com/feed/meteor-meteor-wrapasync

like image 168
Mário Avatar answered Oct 13 '22 14:10

Mário