Fred J.
Fred J.

Reputation: 6039

Meteor Mongo update callback in Fiber

This meteor code fires when the client calls a server-side method which updates a mongo collection but produces the following error:

Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.

Any idea how to get rid of this error so that the update happens? Thanks

//server/methods.js

  'importFromAccess': function(){
    let fileName = 'C:\\Users\\ABC\\Downloads\\tblCstmrs.txt';

   const readInterface = readline.createInterface({
      input: fs.createReadStream(fileName),
      output: process.stdout,
      console: false
    });

    readInterface.on('line', function(line) {
      let custObj = customerMsAccessDataObj(line);
      console.log("will update");
      ContactsCol.update(custObj, { upsert: true }, Meteor.bindEnvironment( function (err, result) {
        if (err) throw err;
        console.log(result);
     })
     );
      console.log("finished update")
    });
 }
 
 //client file
 
   'msAccess_autoShop': (event, fullName) => {
    Meteor.call('importFromAccess');
  }

Upvotes: 2

Views: 130

Answers (1)

Radosław Miernik
Radosław Miernik

Reputation: 4094

The readInterface.on('line', function (line) { ... }) callback is called outside of a fiber. There's a Meteor.bindEnvironment to wrap a callback in a fiber:

readInterface.on('line', Meteor.bindEnvironment(function (line) { ... }));

This will ensure that the callback will have a fiber to use (it'll either create a new one or use the one it was called within).

There's also Meteor.wrapAsync, which transforms a callback-style function into a synchronous one (it's actually async, but fibers take care of it).

Upvotes: 1

Related Questions