mongodbmeteorwebsocketfindfiber

[ 'Parse error: Can\'t wait without a fiber' ]' When trying to do find within Metor


When receiving JSON data via websockets, I'm trying to feed this data into a mongodb within meteor. I'm getting the JSON data fine, but when trying to find whether the data already exists in the database, I keep getting the error: "[ 'Parse error: Can\'t wait without a fiber' ]'.

binance.websockets.miniTicker(markets => {
      //we've got the live information from binance
      if (db.Coins.find({}).count() === 0) {
        //if there's nothing in the database right now
        markets.forEach(function(coin) {
          //for each coin in the JSON file, create a new document
          db.Coins.insert(coin);
        });
      }
    });

Can anyone point me in the right direction to get this cleared up?

Many thanks, Rufus


Solution

  • You execute a mongo operation within an async function's callback. This callback is not bound to the running fiber anymore. In order to connect the callback to a fiber you need to use Meteor.bindEnvironment which binds the fiber to the callback.

    binance.websockets.miniTicker(Meteor.bindEnvironment((markets) => {
      //we've got the live information from binance
      if (db.Coins.find({}).count() === 0) {
        //if there's nothing in the database right now
        markets.forEach(function(coin) {
          //for each coin in the JSON file, create a new document
          db.Coins.insert(coin);
        });
      }
    }));
    

    You should not require to bind to the function within the forEach as they are not async.

    Related posts on SO:

    Meteor.Collection with Meteor.bindEnvironment

    Meteor: Calling an asynchronous function inside a Meteor.method and returning the result

    Meteor wrapAsync or bindEnvironment without standard callback signature

    What's going on with Meteor and Fibers/bindEnvironment()?