简体   繁体   中英

Meteor.call and Meteor.publish: returning Collection.find properly

This is a pub I currently have:

Meteor.publish("searchResults", function (urlString) {
    check(urlString, String);

    Meteor.call('searchDatabase', urlString, function(error, result) {
        if(error) {
            return throwError(error.reason);
        }
        Session.set('searchData', result);
    });

    return [
        Posts.find({_id: {$in: Session.get('searchData')}}),
        Farmers.find({_id: {$in: Session.get('searchData')}})
    ];
});

I originally tried to do this:

Meteor.publish("searchResults", function (urlString) {
    check(urlString, String);

    Meteor.call('searchDatabase', urlString, function(error, result) {
        if(error) {
            return throwError(error.reason);
        }
        return [
            Posts.find({_id: {$in: Session.get('searchData')}}),
            Farmers.find({_id: {$in: Session.get('searchData')}})
        ];
    });
});

Turns out the latter does not return from the pub method. It just returns out of the Meteor.call function, which returns undefined regardless. However, the former keeps giving me a Session is not defined error. What am I doing wrong/What is the right way to get this done? result is an array that has all the _id of the elements in collections that I need to show.

Thanks in advance for the help!

As fuzzybabybunny mentioned, Sessions run on the client only, so the approach you're taking can't work for publications, which run on the server. The method call in the publication is an asynchronous one, so you will have to wait for its result in order to use it to return the database cursor. Try using one of the ways to use an asynchronous call in a synchronous way. Here's an example:

Example on using npm module inside a Meteor method

Of course there are other ways, such as the Future class in the Fibers package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM