0

I want to insert in the Tweets collection every tweets from the stream made with Twit (npm module), inside a method.

Here is my code:

stream: function(hashtag) {
    //Création du stream
    stream = T.stream('statuses/filter', { track: hashtag });
    var currentHashtag = hashtag;

    // Lance le stream
    stream.on('tweet', function (tweet) {
         var userName = tweet.user.screen_name;
            var userTweet = tweet.text;
            var tweetDate = tweet.created_at;
            var profileImg = tweet.user.profile_image_url;

        console.log(userName+" a tweeté: "+userTweet+" le: "+tweetDate);
        console.log("=======================");

        Tweets.insert({user: userName, tweet: userTweet, picture: profileImg, date: tweetDate, hashtag: currentHashtag}, function(error) {
            if(error)
                console.log(error);
        });
    });
}

And here is my error message: [Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor Libraries with Meteor.bindEnvironment. ]

I've tried different solutions in vain, like wrap the Collection insertion in a Fiber(), and I try to use a Meteor.bindEnvironment, but never understand how to properly use it.

Can you help me ?

===================================================

Edit:

I've tried this. With this code, I don't have any errors anymore, but the tweets aren't inserted in my Collection.

    stream.on('tweet', Meteor.bindEnvironment(function(tweet) {
       var tweetToInsert = {
            user: tweet.user.screen_name, 
            tweet: tweet.text, 
            picture: tweet.user.profile_image_url, 
            date: tweet.created_at, 
            hashtag: currentHashtag
        };

        console.log(tweetToInsert.user+" a tweeté: "+tweetToInsert.tweet+" le: "+tweetToInsert.date+" \n "+tweetToInsert.picture+"\n"+tweetToInsert.hashtag);
        console.log("=======================");

        Tweets.insert(tweetToInsert, function(error, result) {
            if(error)
                console.log(error);
            else
                console.log(result);
        });
    }));
Community
  • 1
  • 1
Art2B
  • 185
  • 1
  • 17

1 Answers1

5

You can run a Fiber on insert:

var Fiber = Npm.require('fibers');
Fiber(function () {
   Tweets.insert({user: userName, tweet: userTweet, picture: profileImg, date: tweetDate, hashtag: currentHashtag}, function(error) {
      if(error)
         console.log(error);
    });
}).run();
lfergon
  • 963
  • 15
  • 27